Unable to Redirect to Home Page After User Login Using Redux – Redux Shows Undefined

Hey i am new to Redux and I’m encountering an issue in my React application when attempting to redirect the user to the home page after successful login using Redux and fireBase. Despite dispatching the necessary actions to update the Redux state, I’m facing difficulties with redirection, and when inspecting the Redux state, it shows as undefined. I have verified my actions, reducers, and the usage of the useSelector hook, but the problem persists.
this my code for usersSlice

import { createSlice } from "@reduxjs/toolkit";

export const userSlice = createSlice({
  name: "user",
  initialState: {
    currentUser: null
  },

  reducers: {
    setUser: (state, action) => {
      console.log("set user", action.payload);
      state.currentUser = action.payload;
    },
  },
});

export const { setUser } = userSlice.actions;
export const selectUser = (state) => state.user?.currentUser; // i am using ? because it shows undefind
export default userSlice.reducer;

store

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

export default configureStore({
    reducer: {
        user: userReducer
    }
})

login

import React from "react";
import "./login.css";
import { Link } from "react-router-dom";
import { sendPasswordResetEmail, signInWithEmailAndPassword } from "firebase/auth";
import {auth} from "../config/firebase.config";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { setUser } from "../state/usersSlice";


const Login = () => {

  const [emailL, setEmailL] = useState("");
  const [passL, setPassL] = useState("");
  const [error, setError] = useState("");

const dispatch = useDispatch();
  const signIn = async (e) => {
    e.preventDefault();
    //console.log(email, pass, loginError)
    await signInWithEmailAndPassword(auth, emailL, passL)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        console.log(user.email, user.uid)
        // ...
alert("oged in")
        dispatch(setUser({
          id: user.uid,
          email: user.email
        }))

      })
      .catch((error) => {
        const errorCode = error.code;

        const errorMessage = error.message;
        setError(errorMessage);
      });
  };
  const forgotPass = () => {
    const email = prompt("please enter your email: ");
    sendPasswordResetEmail(auth, email);
    alert("Email sent! check your email inbox to chnage password!!!");
  }
  return (
    <div className="container">
      <div className="login">
        <form className="login-form">
          <h3 className="title">SIGN IN</h3>
          <div className="inputs">
            <InputField
              required
              type={"email"}
              placeholder={"email"}
              className={"email"}
              handleChange={(data) => setEmailL(data)}
            />
            <InputField
              required
              type={"password"}
              placeholder={"Password"}
              className={"password"}
              handleChange={(data) => setPassL(data)}
            />
          </div>
          <button type="submit" onClick={signIn} className="btn log-in-btn">
            Login
          </button>
          <p onClick={forgotPass} className="forgot">FORGOT PASSWORD ?</p>
          <p className="not-accnt">
            NEED AN ACCOUNT ?{" "}
            <span>
              <Link className="sgn-up" to="/register">
                SIGN UP.
              </Link>
            </span>{" "}
          </p>
        </form>
      </div>
      <p style={{ color: "red" }}>{error}</p>
    </div>
  );
};
const InputField = ({ placeholder, handleChange, type }) => {
  const [inputValue, setInputValue] = useState("");
  const handelChangeEvent = (e) => {
    setInputValue(e.target.value);
    handleChange(e.target.value);
  };
  return (
    <input
      required
      type={type}
      placeholder={placeholder}
      value={inputValue}
      onChange={handelChangeEvent}
      className="password"
    />
  );
};

export default Login;

app.js

import "./App.css";
import Login from "./loginRegister/Login";

import Register from "./loginRegister/Register";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";

import Home from "./Home";
import { selectUser } from "./state/usersSlice";
import { useSelector } from "react-redux";

function App() {
  const user = useSelector(selectUser);
  return (
    <div>
      {user ? (
        <Routes>
          <Route index element={<Home />} />
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />
        </Routes>
      ) : (
        <Login />
      )}
    </div>
  );
}

export default App;

main

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import { BrowserRouter, Routes, Route } from "react-router-dom";

import { createStore, combineReducers } from "redux";
import usersSlice from "./state/usersSlice";
import { Provider } from "react-redux";


import './index.css'

const rootReducer = combineReducers({
  mySlice: usersSlice,
});

const store = createStore(rootReducer);


ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Provider store= {store}>
    <BrowserRouter>

    <App />
    </BrowserRouter>

    </Provider>
  </React.StrictMode>,
)

this is redux inspect
Redux inspect shows undefined

Any insights or solutions to resolve this redirection issue would be greatly appreciated. Thank you!

Hydration Error Div in Div In react component

How can i solve Hydration error div in div problem.

I have a component who actually have 2 functionality – fetch and map.
And i have faced hydration error, i don’t know why i faced this issue! sometime it’s give me a error and sometime it’s not showed in my application. how can i solve this?

{
                        tableBodyData?.map((item, index) => <li key={index} className="font-[500] px-[6px] bg-[#2D5BFF] hover:bg-[#0d3deb] flex items-center justify-center gap-x-[2px] duration-100 rounded-[4px] leading-[24px] text-white cross-magic cursor-default text-[12px]  border-none outline-none hover:extraDarkBlue">
                            {item?.tag}
                            <span onClick={() => handleDeleteTags(item)} className="cursor-pointer ml-2"><SettingsWhiteCircleCross /></span>
                        </li>)
                    }

How to make height to occupy its available space?

Actually my problem is Iam trying to render a table with pagination. where header section has search bar. then body section has table and then pagination. But the problem is table grows and scrollbar appears How to fix that? Somebody please tell me the best way to make this layout.

Expecting output is scrollbar should be appeared only in the table body section

```  
 <Stack height="100%" justifyContent={'space-between'}>
      <Box flexGrow={1}>
        <TableContainer>
          <Table stickyHeader>
            <TableHead>
              <HeaderRow
                HeaderData={faxTableHeader}
                order={order}
                orderBy={orderBy}
                onRequestSort={handleRequestSort}
              />
            </TableHead>
            <TableBody>
              <GetRowData />
            </TableBody>
          </Table>
        </TableContainer>
      </Box>
      <Box>
        <CustomPagination />
      </Box>
    </Stack>
```

Vue 3.4 same-name shorthand vs-code support

I recently upgaraded my Vue 3 project to Vue 3.4. When I tried to use same-name shorthand, even though it was working fine, vs-code is highlighting it as an error, I am using volar. Is there any way to make vs-code understand this new Vue 3 syntax?

enter image description here

How do get test in jest for error handling middleware in node-postgres passing for PostgreSQL database in JavaScript (getting undefined)?

I am just starting out with some basic error handling tests in Jest. I have birds-related database and I want to get the test below in my testing file to pass.

//app.test.js

const request = require("supertest")
const db = require("../db/index.js")
const {wing_shapeData,birdsOrdersData,birdsFamiliesData,birdsData,birdwatchersData,rookeryTourData,watcherTourData} = require("../db/data/test-data/index.js")
const seed = require("../db/seed.js")
const app = require("../app.js")

beforeEach(() =>seed({wing_shapeData,birdsOrdersData,birdsFamiliesData,birdsData,birdwatchersData,rookeryTourData,watcherTourData}))

afterAll(() =>db.end())


describe("Endpoint(path) is not recognized and cannot be found for rookery",()=>{

    it("Should return status code 404 when passed bad path",()=>{
        return request(app).get('/api/fjrofjiro303gjvn200').expect(404).then(({ body }) => {
            expect(body.msg).toBe('HTTP 404 error: path cannot be found');
          });
    })
})

When I do npm test app.test.js in the terminal I get this error

__tests__/app.test.js
  Endpoint(path) is not recognized and cannot be found for rookery
    ✕ Should return status code 404 when passed bad path (96 ms)

  ● Endpoint(path) is not recognized and cannot be found for rookery › Should return status code 404 when passed bad path

    expect(received).toBe(expected) // Object.is equality

    Expected: "HTTP 404 error: path cannot be found"
    Received: undefined

      14 |     it("Should return status code 404 when passed bad path",()=>{
      15 |         return request(app).get('/api/fjrofjiro303gjvn200').expect(404).then(({ body }) => {
    > 16 |             expect(body.message).toBe('HTTP 404 error: path cannot be found');
         |                                  ^
      17 |           });
      18 |     })
      19 | })

      at toBe (__tests__/app.test.js:16:34)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.337 s, estimated 1 s
Ran all test suites matching /app.test.js/i.

Here is my part of my app.js file

const express = require('express');
onst app = express();
app.use(express.json())

app.use((req, res, next) => {
    console.log('Request method: ', req.method);
    console.log('Request url: ', req.url);
    let currentdate = new Date(); 
    let datetime = `Date and time request method made(format:day/month/year|hours:minutes:seconds): ${currentdate.getDate()}/${(currentdate.getMonth()+1)}/${currentdate.getFullYear()}|${currentdate.getHours()}:${currentdate.getMinutes()}:${currentdate.getSeconds()}`
    console.log(datetime)
    next()
  });

  const errorLogger = (err,req,res,next) =>{
    console.log(`Error : ${err.message}`)
    next(err)
  }

  const handleNotFound = (err,req,res,next)=>{   
    if(err.status === 404){
      res.status(err.status).send({message: 'HTTP 404 error: path cannot be found'})
    }
    next(err)
    
  }
  const errorResponder = (err,req,res,next) =>{
      if(err.statusCode  && err.message){
      res.status(err.statusCode).send({message: err.message})
      }
      next(err)
  }
  
  const handleServerError = (err, req,res,next) => {
    res.status(500).send(err.message)
  }

  app.use(errorLogger)
  app.use(handleNotFound)
  app.use(errorResponder)
  app.use(handleServerError)


app.get('/api/birds',getAllBirds)

Controller below: invokes the model and deals with the request-response cycle

//birds.controller.js

exports.getAllBirds = (req,res,next) =>{
 const {order1} = req.query
 const {order2} = req.query
 const {sort_byfirst} = req.query
 const {sort_bysecond} = req.query
 const {diet} = req.query
 selectAllBirds(sort_byfirst,order1,diet,sort_bysecond,order2).then((birds)=> res.status(200).send({birds})).catch(next)
}

Model below: accesses the database to retrieve relevant data once database has been seeded with data


//birds.models.js
const db = require('../db/index.js')

exports.selectAllBirds = (sort_byfirst,order1,diet,sort_bysecond,order2) =>{


    const sortbyGreenList1 = ['length_cm','weight_g','wingspan_cm']
    const sortbyGreenList2 = ['common_name']

    const orderbyGreenList = ['ASC','DESC']
    let queryValues = [];
    let queryStr = `SELECT bird_id,common_name,species_name,wing_colour,diet,can_Fly
    ,length_cm,weight_g,lay_season,fun_fact,wingspan_cm,f_id FROM birds
     INNER JOIN bird_families ON birds.f_id = bird_families.family_id`;

    if(sort_byfirst && !sortbyGreenList1.includes(sort_byfirst)){
        return Promise.reject({status: 400, message: 'Invalid sort_byfirst query string'})
    }

    if(sort_bysecond && !sortbyGreenList2.includes(sort_bysecond)){
        return Promise.reject({status: 400, message: 'Invalid sort_bysecond query string'})
    }

    if(order1 && !orderbyGreenList.includes(order1.toUpperCase())){
        return Promise.reject({status: 400, message: 'Invalid order1 query string'})
    }

    if(order2 && !orderbyGreenList.includes(order2.toUpperCase())){
        return Promise.reject({status: 400, message: 'Invalid order2 query string'})
    }
   
    if(diet){
        queryValues.push(`%${diet}%`)
        queryStr += ` WHERE diet ILIKE $1`;
    }

    if(sort_byfirst){//AMEND HERE
        queryStr += ` ORDER BY ${sort_byfirst}`;  

    }
 
    if(order1 && sort_byfirst){
        queryStr += ` ${order1.toUpperCase()}`;
    }

    if(order2 && sort_bysecond && sort_byfirst){
        queryStr += `, ${sort_bysecond} ${order2.toUpperCase()}`;
    }

    return db.query(queryStr,queryValues).then((result)=>{
        if(!(result.rows.length)){
            return Promise.reject({status: 404, err: 'No results found for query'})

        }else{
            return result.rows
        }
    })
}

Different values in an array after assignment, but identical values after logging

I’ve encountered a strange behavior in my JavaScript code that I can’t seem to explain. I have an array of objects (devices), and I deep copy it (_devices) before manipulation. Then, I assign a value to each object in devices, but the values appear to be identical after logging, even though they should be different.

    const _devices = JSON.parse(JSON.stringify(devices)); // Deep copy
    await Promise.all(
    devices.map((dev, idx) => {
        dev.apiProp = data[idx];
        dev.pending = true;
        _devices[idx].pending = true;
        })
    );

    console.log(_devices[0].apiProp, devices[0].apiProp); // Different values in apiProp >>> CORRECT!
    console.log(_devices[0], devices[0]); // Identical values for apiProp, though they should be 
    different

here is a minimal example in JSFiddle

https://jsfiddle.net/51fx6gsj/4/

Decimal function validation on multiple listener

I have the following code.

<table class="display table table-striped responsive nowrap ">
  <tbody id="dataTable" class="table" >
    <tr >
      <td>
      <div class="form-row" style="margin-bottom: 40px;" >
          <div><label>kg</label><input class="form-control pesoformat" type="number" name="kg[]" value="0.00" min="0.00" max="1.00" step="0.01" placeholder="0.00" required ></div>
          <div><label>qty</label><input type="number" name="qta[]" class="form-control" required ></div>                                        
          <div><button type="button" class="btn add" id="btnAdd" >ADD NEW ROW</button></div>
     </div>
      </td>
    </tr>
    </tbody>
</table>

<script>

const table = document.getElementById('dataTable');
const row = table.querySelector('tr');
const renum = () => { 
  let cnt = 0;
  table.querySelectorAll('td:first-child .tst').forEach(input => input.value = ++cnt);
};


table.addEventListener('click', (e) => {
  const tgt = e.target.closest('[type=button]');
  if (!tgt) return
  if (tgt.matches('.add')) {
    const newRow = row.cloneNode(true);
    newRow.querySelectorAll('input[type=text]').forEach(input => input.value = ""); // reset the values
    newRow.querySelectorAll('input[type=number]').forEach(input => input.value = ""); // reset the values
    table.appendChild(newRow);
    renum();
  }
})

var numberElement = document.querySelector(".pesoformat")   
numberElement.addEventListener('change',alterNumber);
function alterNumber(event){
var el = event.target;
var elValue = el.value;
el.value = parseFloat(elValue).toFixed(6);
}

</script>

The problem is that the function that formats the decimal value works only on the first row (under kg input field). When I try to add more rows it doesn’t work anymore.

I also tried to place the function alterNumber into the and change

numberElement.addEventListener('change',alterNumber);

into

this.addEventListener('change',alterNumber);

A complete example here:
https://jsfiddle.net/9sn3dj4f/

but in this case the function worked also on the new row but also on all input fields… and this is not what i want. I only want that function on the kg input field…

any help?

https://jsfiddle.net/9sn3dj4f/

In react my onMouseMove event stops working after onClick event is called

in my app when the cursor moves over a div with an image the handleMouseMove event is called. However, after the user clicks over the div the handleMouseMove stops working. I need to move the cursor outside the window to recover the onMouseMove. Do you have any clue about how to solve this? Chat GPT is not helping with this 🙂

This is the simplified version of my code

import React from "react";

const Finder = () => {
  const handleMouseMove = (e) => {
    console.log("handleMouseMove");
  };

  const handleClick = () => {
    console.log("onClick");
  };

  return (
    <div
      onMouseMove={handleMouseMove}
      onClick={handleClick}
      style={{ backgroundColor: "red", width: 281, height: 610 }}
    >
      <img
        src="/img/Clothing/ClothingGirl1.jpg"
        style={{
          width: 281,
          height: 610,
          border: "1px solid silver",
        }}
        alt={"alt"}
      />
    </div>
  );
};

export default Finder;

Thanks a lot for your help

I am facing an issue where the pointer, when positioned in the middle, activates the adjacent element. I need a solution to this problem

  <!-- display results -->
  <transition name="slide-fade">
    <div class="prize" v-if="isShow == isClicked">
      <div class="prize-container">
        <div class="prize-title">WELL<br /></div>
        <div class="prize-title">DONE!<br /></div>
        <!-- <div class="prize-background">
          <template v-for="(prizeIcon, index) in 9">
            <i class="material-icons">
              {{ prizeIcon }}
            </i>
          </template>
        </div> -->
      </div>
    </div>
  </transition>
</div>
<div v-if="isShow == isClicked" class="flex items-center">
  <span class="prize-item text-4xl font-bold mt-3">
    {{ prize_name }}
  </span>
  <span class="prize-item text-4xl font-bold mt-3 ms-2"> EGY </span>
</div>

<button
  @click="rotateHandler(num)"
  class="py-4 px-20 rounded-[6px] mt-10 hover:bg-white hover:text-black transition-all text-[18px] font-bold foucs:outline-none bg-black text-[#FFF000]"
>
  Spin
</button>

$primary-color: #343baa; $primary-color-dark: #1f1172; $secondary-color: #fff000; $access-color: #ff00ba; $duration: 3s; *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } [v-cloak] { display: none !important; } #wheel { display: flex; justify-content: center; align-items: center; height: 100vh; overflow: hidden; font-family: “Roboto Condensed”, sans-serif; position: relative; background-color: #fff000; user-select: none; flex-direction: column; } .status-container { position: relative; left: 100px; } .toggle { display: flex; background-image: url(“https://raw.githubusercontent.com/HuiyuLiz/vue-lucky-wheel/306abe15b78c71c3cd25ed8eaf97554101fd405e/svg/toggle.svg”); background-position: center; background-size: 100% 100%; background-repeat: no-repeat; width: 100px; height: 120px; position: absolute; left: calc; top: -3%; transition: all 0.3s ease-in; filter: drop-shadow(-3px 5px 0px $primary-color); cursor: pointer; &:hover { transform: rotate(360deg) scale(0.8); } } .game-status { position: absolute; left: 2%; top: 4%; font-size: 2rem; color: $secondary-color; display: flex; justify-content: flex-end; align-items: stretch; margin: 0 auto; flex-direction: column-reverse; font-weight: 700; text-transform: uppercase; width: 250px; height: 600px; } button:focus { outline: 0; } .times { font-size: 2.5rem; line-height: 0.9; display: flex; align-items: center; justify-content: flex-start; margin: 5px 0px; position: relative; color: $primary-color-dark; &::after { position: absolute; content: “x”; font-size: 2.3rem; font-weight: normal; left: 150px; top: 3px; color: $secondary-color; } > span { text-align: right; color: $primary-color-dark; margin-left: 40px; } } .buttons { display: flex; flex-direction: row; justify-content: space-around; } .btn { cursor: pointer; font-family: “Roboto Condensed”, sans-serif; width: 100px; padding: 5px 10px; margin: 10px 5px; font-size: 1rem; font-weight: bold; transition: all 0.3s; &.btn-primary { border: 3px solid #1f1172; color: $secondary-color; background-color: $primary-color; } &.active { border: 3px solid $access-color; color: $access-color; background-color: $primary-color-dark; } &.btn-secondary { border: 3px solid #1f1172; color: $primary-color; background-color: $secondary-color; &:hover { border: 3px solid $secondary-color; color: $secondary-color; background-color: $primary-color-dark; } } } .lucky-wheel { display: flex; width: 550px; height: 550px; border-radius: 550px; justify-content: center; align-items: center; z-index: 3; &::after { content: “”; width: 540px; height: 549px; background-image: url(“../../../assets//svg/_wheel_rounded.svg”); background-position: center; background-size: cover; background-repeat: no-repeat; position: absolute; } .container { display: block; width: 520px; height: 520px; border-radius: 520px; overflow: hidden; position: relative; transform: rotate(-30deg); &.container-large { transform: rotate(-18deg); } } } .pointer-container { display: flex; width: 58px; height: 58px; flex-shrink: 0; justify-content: center; align-items: center; z-index: 9999; position: absolute; color: $access-color; font-size: 2rem; // &::after { // display: block; // content: “PRESS”; // width: 120px; // height: 120px; // border-radius: 120px; // background-color: #1f1172; // line-height: 120px; // text-align: center; // font-weight: bold; // } .pointer { width: 51.99px; height: 75.99px; display: block; background-image: url(/_nuxt/assets/svg/arrow_wheel.svg); background-position: center; background-size: cover; background-repeat: no-repeat; position: absolute; bottom: 4%; transform-origin: 55% 65%; } } .item { position: absolute; display: flex; width: 50%; height: 50%; border: 1px solid #1f1172; top: 0; right: 0; transform-origin: 0% 100%; justify-content: center; align-items: center; } //$n:輪盤數量;$deg每個項目角度 $n: 6; @for $i from 1 through $n { $deg: 360deg / $n; .item-skew:nth-child(#{$i}) { transform: rotate($deg * $i) skewY($deg – 90

Checking form input fields before submittion

I’m solving one of the FEM challenges where I’m requested to create a form, and check that all fields are filled properly before submitting for the form. The solution should be in react JS as I solved the problem using vanilla javascript before.

I have created the form with all input fields but I have a problem in the email field. The form is made up of 4 input fields :

  1. First Name
  2. Last Name
  3. Email
  4. Password

The bug happened when I filled up the first 3 fields for example correctly, then left the password field empty. Then if I fill the password field, and enter an invalid email in the email field, the form submits without stopping for an invalid email address.
Live Site

import { useState } from "react";

const Subscription = () => {
  const [userName, setUserName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [userNameField, setUserNameField] = useState(true);
  const [lastNameField, setLastNameField] = useState(true);
  const [emailField, setEmailField] = useState(true);
  const [passwordField, setPasswordField] = useState(true);

  function handleSubmit(e) {
    e.preventDefault();

    if (!userName) {
      setUserNameField(false);
    } else {
      setUserNameField(true);
    }
    if (!lastName) {
      setLastNameField(false);
    } else {
      setLastNameField(true);
    }
    // check if email is valid or not
    const regex_pattern =
      /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    if (regex_pattern.test(email)) {
      setEmailField(true);
    } else {
      setEmailField(false);
    }

    if (!password) {
      setPasswordField(false);
    } else {
      setPasswordField(true);
    }

    if (userName && lastName && emailField && password) {
      e.target.submit();
    }
  }
  return (
    <div className="flex-1">
      <p className="bg-Blue text-white py-5 px-5 font-bold rounded-2xl mb-[4px] lg:text-center">
        Try it free 7 days &nbsp;
        <span className="text-[#d9d5fb] font-light">
          then <br className="sm:hidden" />
          $20/mo. thereafter
        </span>
      </p>
      <form
        action="https://httpbin.org/post"
        method="POST"
        className="bg-white rounded-2xl px-8 mt-6"
        noValidate
        onSubmit={handleSubmit}
      >
        <fieldset>
          <div className="relative">
            <input
              type="text"
              placeholder="First Name"
              name="FirstName"
              value={userName}
              onChange={(e) => setUserName(e.target.value)}
              className={!userNameField && "input-error"}
            />
            <p className={userNameField ? "hidden" : "error-message"}>
              First name cannot be empty
            </p>
            <img
              src="images/icon-error.svg"
              alt="error"
              className={
                userNameField ? "hidden" : "absolute top-[38%] right-[2.75rem]"
              }
            />
          </div>
          <div className="relative">
            <input
              type="text"
              placeholder="Last Name"
              name="LastName"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              className={!lastNameField && "input-error"}
            />
            <p className={lastNameField ? "hidden" : "error-message"}>
              Last name cannot be empty
            </p>
            <img
              src="images/icon-error.svg"
              alt="error icon"
              className={
                lastNameField ? "hidden" : "absolute top-[38%] right-[2.75rem]"
              }
            />
          </div>
          <div className="relative">
            <input
              type="email"
              placeholder="Email Address"
              name="Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className={!emailField && "input-error"}
            />
            <p className={emailField ? "hidden " : "error-message"}>
              Looks like this is not an email
            </p>
            <img
              src="images/icon-error.svg"
              alt="error icon"
              className={
                emailField ? "hidden" : "absolute top-[38%] right-[2.75rem]"
              }
            />
          </div>
          <div className="relative">
            <input
              type="password"
              placeholder="Password"
              name="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className={!passwordField && "input-error"}
            />

            <p className={passwordField ? "hidden " : "error-message"}>
              Password cannot be empty
            </p>
            <img
              src="images/icon-error.svg"
              alt="error icon"
              className={
                passwordField ? "hidden" : "absolute top-[38%] right-[2.75rem]"
              }
              id="last-error-icon"
            />
          </div>
          <button className="uppercase bg-Green rounded-md p-[0.75em] pt-[1.5em] text-white w-full mt-2 font-semibold tracking-wider mb-4">
            Claim your free trial
          </button>
          <p className="text-[10px] text-[#d2d1d7] font-semibold text-center mb-8">
            By clicking the button, you are agreeing to
            <br className="lg:hidden" />
            our
            <span className="text-Red">Terms and Services</span>
          </p>
        </fieldset>
      </form>
    </div>
  );
};

export default Subscription;

my question is: what changes to the email related code need to be done to prevent the form from submitting?

My localstorage array values not persisting after reload



import React from 'react'
import Modal from './Modal'
import 'bootstrap/dist/css/bootstrap.min.css';
import Task from './Task';
import { useState, useEffect } from 'react'
export default function AppBody() {
    // const [count, setCount] = useState(0)
    const [showModel, setVisibility] = useState(false);
    const [taskList, updateTaskList] = useState([]);
    const [current, setCurrent] = useState("");
    const openModal = () => {
        setVisibility(true);
    }
    const closeModal = () => {
        setVisibility(false);
    }
    const handleOnAdd = () => {
        const obj = {
            id: taskList.length + 1,
            title: current,
            isComplete: false
        }
        updateTaskList([...taskList, obj]);
        setVisibility(false);

        
        console.log('Task list updated locally');

        // setCurrent("");
    }
    useEffect(() => {
        try {
            const storedTasks = localStorage.getItem("taskList");
            console.log("for first render only");
            if (storedTasks) {
                updateTaskList(JSON.parse(storedTasks));
            } else {
                console.log("No tasks found in local storage");
            }
        } catch (error) {
            console.error("Error retrieving data from local storage:", error);
        }
    }, []);


    useEffect(() => {
        localStorage.setItem('taskList', JSON.stringify(taskList));
        console.log(taskList);
    }, [taskList]);

    const handleStatusChange = (id, status) => {
        const updatedTasks = taskList.map(task => {
            if (task.id === id) {
                return { ...task, isComplete: status }; // Update the status of the task with the matching id
            }
            return task;
        });
        updateTaskList(updatedTasks);//here actuall object returns and updated in actual array
    }
    return (
        <>
            <div className="add" onClick={openModal}><img src="./src/assets/icons8-plus.svg" alt="" /></div>
            <Modal adder={handleOnAdd} setCurrent={setCurrent} visibility={showModel} close={closeModal} />
            <div className='cardsContainer'>
                {
                    taskList.map((item) => {
                        return <Task handleStatusChange={handleStatusChange} key={item.id} taskNo={item.id} current={item.title} status={item.isComplete} />
                    })
                }
            </div>
        </>
    )
}
import React from 'react'
import Modal from './Modal'
import 'bootstrap/dist/css/bootstrap.min.css';
import Task from './Task';
import { useState, useEffect } from 'react'
export default function AppBody() {
    // const [count, setCount] = useState(0)
    const [showModel, setVisibility] = useState(false);
    const [taskList, updateTaskList] = useState([]);
    const [current, setCurrent] = useState("");
    const openModal = () => {
        setVisibility(true);
    }
    const closeModal = () => {
        setVisibility(false);
    }
    const handleOnAdd = () => {
        const obj = {
            id: taskList.length + 1,
            title: current,
            isComplete: false
        }
        updateTaskList([...taskList, obj]);
        setVisibility(false);

        
        console.log('Task list updated locally');

        // setCurrent("");
    }
    useEffect(() => {
        try {
            const storedTasks = localStorage.getItem("taskList");
            console.log("for first render only");
            if (storedTasks) {
                updateTaskList(JSON.parse(storedTasks));
            } else {
                console.log("No tasks found in local storage");
            }
        } catch (error) {
            console.error("Error retrieving data from local storage:", error);
        }
    }, []);


    useEffect(() => {
        localStorage.setItem('taskList', JSON.stringify(taskList));
        console.log(taskList);
    }, [taskList]);

    const handleStatusChange = (id, status) => {
        const updatedTasks = taskList.map(task => {
            if (task.id === id) {
                return { ...task, isComplete: status }; // Update the status of the task with the matching id
            }
            return task;
        });
        updateTaskList(updatedTasks);//here actuall object returns and updated in actual array
    }
    return (
        <>
            <div className="add" onClick={openModal}><img src="./src/assets/icons8-plus.svg" alt="" /></div>
            <Modal adder={handleOnAdd} setCurrent={setCurrent} visibility={showModel} close={closeModal} />
            <div className='cardsContainer'>
                {
                    taskList.map((item) => {
                        return <Task handleStatusChange={handleStatusChange} key={item.id} taskNo={item.id} current={item.title} status={item.isComplete} />
                    })
                }
            </div>
        </>
    )
}
import React from 'react'
import Modal from './Modal'
import 'bootstrap/dist/css/bootstrap.min.css';
import Task from './Task';
import { useState, useEffect } from 'react'
export default function AppBody() {
    // const [count, setCount] = useState(0)
    const [showModel, setVisibility] = useState(false);
    const [taskList, updateTaskList] = useState([]);
    const [current, setCurrent] = useState("");
    const openModal = () => {
        setVisibility(true);
    }
    const closeModal = () => {
        setVisibility(false);
    }
    const handleOnAdd = () => {
        const obj = {
            id: taskList.length + 1,
            title: current,
            isComplete: false
        }
        updateTaskList([...taskList, obj]);
        setVisibility(false);

        
        console.log('Task list updated locally');

        // setCurrent("");
    }
    useEffect(() => {
        try {
            const storedTasks = localStorage.getItem("taskList");
            console.log("for first render only");
            if (storedTasks) {
                updateTaskList(JSON.parse(storedTasks));
            } else {
                console.log("No tasks found in local storage");
            }
        } catch (error) {
            console.error("Error retrieving data from local storage:", error);
        }
    }, []);


    useEffect(() => {
        localStorage.setItem('taskList', JSON.stringify(taskList));
        console.log(taskList);
    }, [taskList]);

    const handleStatusChange = (id, status) => {
        const updatedTasks = taskList.map(task => {
            if (task.id === id) {
                return { ...task, isComplete: status }; // Update the status of the task with the matching id
            }
            return task;
        });
        updateTaskList(updatedTasks);//here actuall object returns and updated in actual array
    }
    return (
        <>
            <div className="add" onClick={openModal}><img src="./src/assets/icons8-plus.svg" alt="" /></div>
            <Modal adder={handleOnAdd} setCurrent={setCurrent} visibility={showModel} close={closeModal} />
            <div className='cardsContainer'>
                {
                    taskList.map((item) => {
                        return <Task handleStatusChange={handleStatusChange} key={item.id} taskNo={item.id} current={item.title} status={item.isComplete} />
                    })
                }
            </div>
        </>
    )
}

as i have various components in my such as Modal task Navbar and i am passing states to that component and functions also such as adder to understand modal my main issue is my localstorage values not persisting but when i remove react strict mode my application works fine.

my application works well after removing react strict mode

Can’t get popperModifiers to work in react-datepicker

I am working with react component known as DatePicker in my project and trying to modfiy its position through popperModifiers argument but it doesn’t seem to work.

<DatePicker selected={dateValue} onChange={date => setDateValue(date)} id='res-date' onMonthChange={handleMonthChange} popperPlacement='bottom' popperModifiers={[
                {
                    name: 'offset',
                    phase: 'main',
                    options: {
                        offset: [0, 10],
                    },
                    fn: data => {
                        console.log(data);
                        return data;
                    },
                },
            ]}/>

I don’t know how to modify offset and this is not working.

Hex codes and block host

How can I decode hex codes? The file works on localhost, but when I upload it to hosting, it doesn’t work. I think there is a code such as domain blocking, but I couldn’t find it. I would be glad if you could help me.

full codes in
https://jsfiddle.net/tuncay0063/0eoyhs3a/

(function (_0x40f709, _0x495323) {
  var _0x439807 = _0x1e9f, _0x402ce1 = _0x40f709();
  while (true) {
    try {
      var _0x60e3b6 = -parseInt(_0x439807(450)) / 1 + parseInt(_0x439807(429)) / 2 * (-parseInt(_0x439807(350)) / 3) + -parseInt(_0x439807(412)) / 4 + parseInt(_0x439807(328)) / 5 + parseInt(_0x439807(413)) / 6 * (parseInt(_0x439807(430)) / 7) + -parseInt(_0x439807(353)) / 8 + parseInt(_0x439807(366)) / 9 * (parseInt(_0x439807(377)) / 10);
      if (_0x60e3b6 === _0x495323) break; else _0x402ce1.push(_0x402ce1.shift());
    } catch (_0x36b06e) {
      _0x402ce1.push(_0x402ce1.shift());
    }
  }
}(_0x3140, 202791), function (_0xdde188) {
  "use strict";
  var _0xcbd799 = _0x1e9f;
  function _0x4aa18b(_0x111b06) {
    var _0x532d68 = _0x1e9f;
    if (!(parseInt(_0x111b06[_0x532d68(453)]) === _0x111b06[_0x532d68(453)])) return false;
    for (var _0x3aa7d2 = 0; _0x3aa7d2 < _0x111b06[_0x532d68(453)]; _0x3aa7d2++) {
      if (!(parseInt(_0x111b06[_0x3aa7d2]) === _0x111b06[_0x3aa7d2]) || _0x111b06[_0x3aa7d2] < 0 || _0x111b06[_0x3aa7d2] > 255) return false;
    }
    return true;
  }
  function _0x280ac1(_0xab4333, _0x451d59) {
    var _0x2e638a = _0x1e9f;
    if (_0xab4333[_0x2e638a(443)] && _0xab4333[_0x2e638a(446)] === _0x2e638a(409)) return _0x451d59 && (_0xab4333[_0x2e638a(334)] ? _0xab4333 = _0xab4333[_0x2e638a(334)]() : _0xab4333 = Array[_0x2e638a(333)][_0x2e638a(334)][_0x2e638a(386)](_0xab4333)), _0xab4333;
    if (Array[_0x2e638a(426)](_0xab4333)) {
      if (!_0x4aa18b(_0xab4333)) throw new Error(_0x2e638a(351) + _0xab4333);
      return new Uint8Array(_0xab4333);
    }
    if (parseInt(_0xab4333[_0x2e638a(453)]) === _0xab4333[_0x2e638a(453)] && _0x4aa18b(_0xab4333)) return new Uint8Array(_0xab4333);
    throw new Error("Wasabi error 1");
  }
  function _0x579fef(_0x469d38) {
    return new Uint8Array(_0x469d38);
  }
  function _0x42e5b4(_0x1d2132, _0x80aa84, _0x58eef6, _0x48d9c7, _0x5c52a6) {
    var _0x529822 = _0x1e9f;
    (_0x48d9c7 != null || _0x5c52a6 != null) && (_0x1d2132[_0x529822(334)] ? _0x1d2132 = _0x1d2132[_0x529822(334)](_0x48d9c7, _0x5c52a6) : _0x1d2132 = Array.prototype[_0x529822(334)][_0x529822(386)](_0x1d2132, _0x48d9c7, _0x5c52a6)), _0x80aa84[_0x529822(394)](_0x1d2132, _0x58eef6);
  }
  var _0x4ba0a0 = function () {
    function _0x59a6ed(_0x438966) {
      var _0x12abf8 = _0x1e9f, _0x2cbdcd = [], _0x5a1891 = 0;
      while (_0x5a1891 < _0x438966[_0x12abf8(453)]) {
        var _0x4dc1aa = _0x438966[_0x5a1891];
        if (_0x4dc1aa < 128) _0x2cbdcd[_0x12abf8(368)](String[_0x12abf8(374)](_0x4dc1aa)), _0x5a1891++; else _0x4dc1aa > 191 && _0x4dc1aa < 224 ? (_0x2cbdcd[_0x12abf8(368)](String[_0x12abf8(374)]((_0x4dc1aa & 31) << 6 | _0x438966[_0x5a1891 + 1] & 63)), _0x5a1891 += 2) : (_0x2cbdcd.push(String.fromCharCode((_0x4dc1aa & 15) << 12 | (_0x438966[_0x5a1891 + 1] & 63) << 6 | _0x438966[_0x5a1891 + 2] & 63)), _0x5a1891 += 3);
      }
      return _0x2cbdcd[_0x12abf8(346)]("");
    }
    return {fromBytes: _0x59a6ed};
  }(), _0x1acba5 = function () {
    function _0x2135df(_0x4718a6) {
      var _0x3a0d5a = _0x1e9f, _0x191efc = [];
      for (var _0x57f822 = 0; _0x57f822 < _0x4718a6[_0x3a0d5a(453)]; _0x57f822 += 2) {
        _0x191efc.push(parseInt(_0x4718a6.substr(_0x57f822, 2), 16));
      }
      return _0x191efc;
    }
    return {toBytes: _0x2135df};
  }()

It works as a desktop html file, but it doesn’t work on hosting.