how to make the expanded part come to the same height of the others?

i ll attach my code here please suggest me a way to fix this issue.I m tryying to make a html css page with a expanding item list on side and i stucked on this issue.I need expanded part also to be equally same verticle postion as the figma design image i attached.(I attached figma design at the end).Please suggest me a way,
enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Navbar</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        /* Navbar styles */
        .navbar {
            display: flex;
            flex-direction: column;
            background-color: #6BA1FF;
            margin-top: 0;
            padding: 0;
        }
        .contactLine, .logoLine {
            display: flex;
            margin: 0;
        }
        .contactLine h5 {
            margin-right: 20px;
        }
        .logoLine img {
            margin: 0;
            margin-bottom: 2px;
        }
        #logo{
            width: 160px;
            height: 50px;
        }
        #searchBar {
            width: 350px;
            height: 40px;
            margin-left: 20px;
            border-radius: 15px;
            border: none;
        }
        #searchButton{
            width: 50px;
            height: 42px;
            border: none;
            background-color: #274E91;
            border-top-right-radius: 15px;
            border-bottom-right-radius: 15px;
            position: relative;
            top: 4px;
            right: 54px;
            z-index: 999;
        }
        .search{
            position: relative;
            left: 280px;
        }
        #loginRegBtn{
            background-color: #6BA1FF;
            border: none;
            position: relative;
            left: 350px;
            font-size: x-large;
        }

        /* Sidebar styles */
        #sidebar {
            width: 200px;
            position: absolute;
            top: 102px;
            background-color: whitesmoke;
            box-shadow: rgba(0, 0, 0,0.6);
            border-radius: 10px;
        }
        #sidebar ul {
            position: relative;
            list-style-type: none;
        }
        #sidebar ul li a {
            display: flex;
            align-items: center;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 1.00em;
            text-transform: capitalize;
            color: #757576;
            text-decoration: none;
            padding: 10px 30px;
            height: 30px;
            transition: 0.1s ease;
        }
        #sidebar ul li a:hover {
            background:#757576;
            color: rgb(56, 141, 251);
        }
        #sidebar ul ul {
            position: absolute;
            left: 165px;
            width: 200px;
            top: 0;
            display: none;
            background: whitesmoke;
            box-shadow: 3px 3px 10px rgba(0, 0,0, 0.1);
            border-radius: 20px;
        }
        #sidebar ul .dropdw {
            position: relative;
        }
        #sidebar ul .dropdw:hover ul {
            display: initial;
        }
    </style>
</head>
<body>
<div class="navbar">
    <div class="contactLine">
        <h5>Call us for web and orders: 076 4881254</h5>
        <h5>Email: [email protected]</h5>
    </div>
    <div class="logoLine">
        <img src="logo.png" alt="logo" id="logo">
        <div class="search">
            <input type="text" placeholder="Search...." id="searchBar">
            <button id="searchButton"><svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 50 50"
                                           style="fill:#FFFFFF;">
                <path d="M 21 3 C 11.601563 3 4 10.601563 4 20 C 4 29.398438 11.601563 37 21 37 C 24.355469 37 27.460938 36.015625 30.09375 34.34375 L 42.375 46.625 L 46.625 42.375 L 34.5 30.28125 C 36.679688 27.421875 38 23.878906 38 20 C 38 10.601563 30.398438 3 21 3 Z M 21 7 C 28.199219 7 34 12.800781 34 20 C 34 27.199219 28.199219 33 21 33 C 13.800781 33 8 27.199219 8 20 C 8 12.800781 13.800781 7 21 7 Z"></path>
            </svg></button>
            <button id="loginRegBtn" ><i>login/register</i></button>
        </div>
    </div>
</div>
<div id="sidebar">
    <nav >
        <ul>
            <li class="dropdw"><a href="">A/L Division</a>
                <ul>
                    <li><a href="">Science/Maths Stream</a></li>
                    <li><a href="">Commerce Stream</a></li>
                    <li><a href="">Art Stream</a></li>
                    <li><a href="">Technology Stream</a></li>
                    <li><a href="">Common Stream</a></li>
                </ul>
            </li>
            <li class="dropdw"><a href="">O/L Division</a>
                <ul>
                    <li><a href="">Grade 10</a></li>
                    <li><a href="">Grade 11</a></li>
                    <li><a href="">O/L Exam</a></li>
                </ul>
            </li>
            <li class="dropdw"><a href="">Intermediate Division</a>
                <ul>
                    <li><a href="">Grade 9</a></li>
                    <li><a href="">Grade 8</a></li>
                    <li><a href="">Grade 7</a></li>
                    <li><a href="">Grade 6</a></li>
                </ul>
            </li>
            <li class="dropdw"><a href="">Primary Division</a>
                <ul>
                    <li><a href="">Grade 1/2</a></li>
                    <li><a href="">Grade 3/4/5</a></li>
                    <li><a href="">Scholarship Exam</a></li>
                </ul>
            </li>
            <li class="dropdw"><a href="">Common Division</a>
                <ul>
                    <li><a href="">Entertainment</a></li>
                    <li><a href="">General Knowledge</a></li>
                    <li><a href="">Excercise Book</a></li>
                    <li><a href="">Other Books</a></li>
                </ul>
            </li>
        </ul>
    </nav>
</div>
</body>
</html>

I expect to get expanding elements also to be on same verticle position as first level of elements(Al ,Ol),As the second image i shown, for refferance i can share the figma design i created.text.

Thanks

Using one state object for multiple React components and how to create component on button click

I’m new to react, and seems like I’m understanding core concept it’s functionality, but at the same time I feel stuck with a problem which should to be easily-solved with React to my opinion.

I’m building a CV builder app, and it has 3 sections.

  1. Personal Information
  2. Education
  3. Work experience

I know how to use state where each component has it’s own unique values using same state (I mean when you destruct useState on top of the component itself.
I know how to use state on the parent container and make values be accessing across components (For example fetch some personal information and them use another component to render it elsewhere on the screen)
What I don’t know is how to create multiple instances of same component where all components use same State object.
What I don’t know is how to render those object separately in another component.

This is Education component that collects input and saves it in State object.

function Education({ education, handleChange}) {
  const [isOpen, setIsOpen] = useState(true);
  const [isActive, setIsActive] = useState(false);

  function openClose() {
    setIsOpen(!isOpen);
  }

  return (
    <div className="education-set">
      {isActive && <button onClick={() => setIsActive(true)}>Close</button>}
      {!isActive && (
        <>
          <button onClick={openClose}>{isOpen ? 'Close' : 'Open'}</button>
          {isOpen && (
            <form id="education-form">
              <label htmlFor="institution">University: </label>
              <input type="text" name="institution" value={education.institution} onInput={handleChange} />
              <label htmlFor="degree">Degree:</label>
              <input value={education.degree} name="degree" onChange={handleChange} />
              <label htmlFor="location">Location:</label>
              <input value={education.educationLocation} name="educationLocation" onChange={handleChange} />
              <div className="date-wrapper">
                <label>Start date:</label>
                <input value={education.startDate} type="date" name="startDate" onInput={handleChange} />
                <label>End date:</label>
                <input value={education.endDate} type="date" name="endDate" onInput={handleChange} />
              </div>
              <div className="description-wrapper">
                <label htmlFor="description">Description:</label>
                <textarea value={education.description} name="description" onChange={handleChange}></textarea>
              </div>
              <button type="submit" onClick={appendCurrEducation}>
                Save
              </button>
            </form>
          )}
        </>
      )}
    </div>
  );
}

This is how I declare useState for that component in App.jsx

 const [educationArray, setEducationArray] = useState([]);

  const [currentEducation, setCurrEducation] = useState({
    institution: '',
    degree: '',
    educationLocation: '',
    startDate: '',
    endDate: '',
    description: '',
    id: uniqid(),
  });

This function keeps the updates currentEducation object

 function handleEducationChange(event) {
    const { name, value } = event.target;
    setCurrEducation((prevState) => {
      return { ...prevState, [name]: value };
    });
  }

With this function I try push instance of currentEducation object to educationArray(to be able to use map method to render it)

  function handleAddEducation() {
    setEducationArray([...educationArray, currentEducation]);
    setCurrEducation({
      degree: '',
      institution: '',
      educationLocation: '',
      startDate: '',
      endDate: '',
      id: uniqid(),
    });
  }

And this is how I try to render new Instance of Education component clicking on ‘+’ button

<div className="education">
          <h1>Education</h1>
          {educationArray.map((education, index) => (
            <div key={index}>
              {
                <Education
                  education={currentEducation}
                  setCurrEducation={setCurrEducation}
                  handleChange={handleEducationChange}
                />
              }
            </div>
          ))}
          <button id="add-education-button" onClick={handleAddEducation}>
            +
          </button>
        </div>

What I receive: On first click to ‘+’ button, educationArray.length is 0. Only on second click to ‘+’ button educationArray.length is 1. And when I type any of the inputs, all instances print simultaneously.

Excuse me for long post, I’m sure someone has faced it before and must be newbie struggle. Thank you!

Getting POST http://127.0.0.1:8080/generate 405 (Method Not Allowed) – express – cors

I’m trying to input json into an html box, and have the json get html from a folder called ‘modules’, and return the output as a preview in the html. I’m getting an error in the request. POST http://127.0.0.1:8080/generate 405 (Method Not Allowed) I cannot figure this out, any help would be great. I think i just keep guessing and have messed up the code now. Am i not pointing to the localhost correctly? I’m using http://127.0.0.1:8080/
Thanks.

app.js:

const cors = require('cors');

const app = express();

// Enable CORS middleware
app.use(cors());

// Define your routes here

// Start the server
const PORT = process.env.PORT || 127.0 .0 .1: 8080;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

import cors from 'cors';
// Enable CORS for specific origin
app.use(cors({
    origin: 'http://127.0.0.1:8080' // Change this to your frontend URL
}));

app.get('/', (req, res) => {
    res.send('Hello World!')
});

// Route to handle form submission and generate HTML
app.post('/generate', (req, res) => {
    try {
        // Get JSON input from request body
        const jsonInput = req.body;

        // Generate HTML based on parsed JSON data
        const htmlOutput = generateHtml(jsonInput);

        // Return HTML response
        res.send(htmlOutput);
    } catch (error) {
        // Return error message if JSON parsing fails
        res.status(400).send(error.message);
    }
});

// Function to generate HTML based on parsed JSON data
function generateHtml(parsedData) {
    // Implement the logic to generate HTML from parsed JSON data
    return "Generated HTML";
}

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Generator</title>
    <style>
        /* CSS for split layout */
        .container {
            display: flex;
        }
        .left {
            width: 50%;
            padding: 20px;
            box-sizing: border-box;
            border-right: 1px solid #ccc;
        }
        .right {
            width: 50%;
            padding: 20px;
            box-sizing: border-box;
        }
        .preview {
            border: 1px solid #ccc;
            padding: 10px;
            height: 100%;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <h1>HTML Generator</h1>
    <div class="container">
        <!-- Left side for JSON input -->
        <div class="left">
            <h2>Input JSON</h2>
            <textarea id="json_input" rows="20" cols="50"></textarea><br>
            <button onclick="updatePreview()">Generate HTML</button>
        </div>
        <!-- Right side for HTML preview -->
        <div class="right">
            <h2>Preview</h2>
            <div class="preview" id="html_preview"></div>
        </div>
    </div>

    <!-- JavaScript for live preview -->
    <script>
        const jsonInput = document.getElementById('json_input');
        const htmlPreview = document.getElementById('html_preview');
    
        // Function to update HTML preview
        function updatePreview() {
            try {
                // Call Express route to generate HTML
                fetch('http://127.0.0.1:8080/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ json_input: jsonInput.value })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch HTML');
                    }
                    return response.text();
                })
                .then(htmlData => {
                    console.log('Received HTML data:', htmlData);
                    htmlPreview.innerHTML = htmlData;
                })
                .catch(error => {
                    console.error('Error:', error);
                    htmlPreview.innerHTML = `<p>Error: ${error.message}</p>`;
                });
            } catch (error) {
                console.error('Error:', error);
                htmlPreview.innerHTML = `<p>Error: ${error.message}</p>`;
            }
        }
    </script>
    
</body>
</html>

Laravel application setup problem with socket.io

I tried to use socket.io with laravel but i am unable to do so. I am not getting any proper documentation to integrate socket.io with laravel. I follwed some documentation of LARACAST but there is old doc is available that was not able to solve the problem. Please anyone come with the proper integration of socket.io with laravel. i am waiting for you response..

i tried to integrate socket.io with laravel but could not do that.

How to trigger a vuefileagent from another button

I am using this snippet of code

<div id="imageChooser">
                <vuefileagent
                    ref="vueFileAgent"
                    :multiple="false"
                    :deletable="true" :uploadUrl="uploadUrl" meta="false"
                    :accept="'image/*'" :maxSize="'10MB'" :maxFiles="1"
                    @onClick="onUpload($event)"
                    @upload="onUpload($event)" compact="true"
                    @select="onSelect" :helpText="'Choose an image image'"
                    :errorText="{
              type: 'Invalid file type. Only images allowed',
              size: 'Files should not exceed 10MB in size',
            }" v-model="foodImages"></vuefileagent>

This is a image selector basically.
What i wanna do is use another button to simulate clicking on it.

I tried to add a button with @onClick=”onUpload” but it doesnt work becasuse the way these functions work.

methods: {
               
                successCallback(data) {
                    this.analyzedImage = data;
                    this.analyzed = true;
                    window.AppInventor.setWebViewString(data.category.name);
                    console.log(data.category.name);
                    let self = this;
                    Vue.nextTick(function () {
                        self.animate();
                    });
                },
                onUpload(responses) {
                    this.successCallback(responses[0].data);
                    console.log("OnUpload");
                },
                onSelect(event) {
                    this.analyzed = false;
                    console.log("OnSelect");
                    this.uploadFiles();
                },
                uploadFiles: function () {
                    console.log("uploadFiles");
                    this.$refs.vueFileAgent.upload(this.uploadUrl + '?apiKey=' + this.spoonacularApiKey, this.uploadHeaders, this.foodImages);
                }
            }

Use a textbox to count number of visible rows of html table

I currently count the number of visible rows in an html table, before and after applying a search. The result count is placed into the textbox by an onclick event of the button “results”. Is it possible to get the result count directly in the text box, updated on change of the number of visible rows?

html:
results

The function works fine onclick of the button. Textbox onclick also works, but I would like to avoid the clicks and have the value auto-updating in the textbox.

Facing issue in playing audio chunks which are received from the backend server

My Backend is on Fast API and i am using StreamingResponse of Fast API to send the each audio chunk which i am receiving it from the AI Model

like this StreamingResponse(func(query_engine, query), media_type=”audio/wan”)

In the first code snippet i am able to hear the audio once all the chunks are received

In the second code snippet i am trying to play audio chunk by chunk but unable to do that

useEffect(() => {
    if (!finalSpeechToText) return;
    function getResult() {
      const audioCtx = new AudioContext();
      const data = {
        model: "aura-luna-en",
        text: finalSpeechToText,
      };
      fetch("http://localhost:8000/api/v1/query/useChat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => response.arrayBuffer())
        .then((buffer) => {
          console.log("buffer", buffer);
          return audioCtx.decodeAudioData(buffer);
        })
        .then((audioData) => {
          console.log("audioData", audioData);
          const source = audioCtx.createBufferSource();
          source.buffer = audioData;
          source.connect(audioCtx.destination);
          source.start(0);
        })
        .catch((error) => {
          console.log(error);
        });
    }
    getResult();
  }, [finalSpeechToText]);

Here i am get the response and able to listen the audio completely but it is not playing chunk by chunk
buffer & audioData

useEffect(() => {
    if (!finalSpeechToText) return;
    const audioCtx = new AudioContext();
    async function getResult() {
      const data = {
        model: "aura-luna-en",
        text: finalSpeechToText,
      };
      const response = await fetch(
        "http://localhost:8000/api/v1/query/useChat",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }
      );
      const reader = response.body.getReader();
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          return;
        }
        console.log("buffer", value);
        console.log("value.buffer", value.buffer);
        try {
          await new Promise((res) => {
            setTimeout(res, 5000);
          });
          const audioData = await audioCtx.decodeAudioData(value.buffer);
          const source = audioCtx.createBufferSource();
          source.buffer = audioData;
          source.connect(audioCtx.destination);
          source.start(0);
        } catch (error: any) {
          console.log(error.message);
        }
      }
    }
    getResult();
  }, [finalSpeechToText]);

Here each chunk is getting printed after every 5 seconds and i am getting an error
Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data
the value of “value.buffer” is same as the audio Data in the above image

I want to play each audio chunk in the browser as soon as i get it;

Property ‘id’ does not exist on type ‘void’.ts(2339) any [closed]

Property ‘id’ does not exist on type ‘void’.ts(2339)enter image description here

Property ‘id’ does not exist on type ‘void’.ts(2339)
i am trying lot of way i have no idea how to solve this problmes
In TypeScript, the error message “Property ‘id’ does not exist on type ‘void’.ts(2339)” typically occurs when you’re trying to access a property on a value that TypeScript thinks is of type ‘void’. This means that TypeScript believes the value you’re trying to access the property on doesn’t actually have any properties because it’s considered to be void, which is a lack of a value.

Using hashes for Content Security Policy in statically generated sites (SSR) in Next.js 13.5

I’m trying to understand how to implement a strict CSP in Next.js 13.5 using SSG. This is a simple informational site under 20 pages including a locally-served MDX blog. It’s JS based, not Typescript. I don’t require server-side rendering and would like to avoid it. This should be possible with a hash-based CSP. But the Next.js documentation only addresses strict CSP with SSR and nonces:

https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy

I’m particularly puzzled by this section in the above doc:

“For applications that do not require nonces, you can set the CSP header directly in your next.config.js file:”

    default-src 'self';
    script-src 'self' 'unsafe-eval' 'unsafe-inline';
    style-src 'self' 'unsafe-inline';
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    upgrade-insecure-requests;
`
 
module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: cspHeader.replace(/n/g, ''),
          },
        ],
      },
    ]
  },
}

I did that, but Lighthouse and all other SEO tools are flagging the configuration as unsecure due to all the unsafe declarations.

So my questions are:

  • How do I determine whether my site ‘requires nonces’ as stated in the
    Next.js docs? The config in the example isn’t strict CSP because of
    unsafe-inline and Google could conceivably flag it in a Pure Spam
    action.
  • How can I achieve strict CSP with hashes using Javascript with Next.js and SSG?
    And finally:
  • What good is SSG if there’s no way to conform to Google guidelines for strict CSP? Doesn’t that make SSG basically useless from a security standpoint?

Thanks for any help.

Webpack: No loaders are configured to process this file in Custom React js lib

I am creating a custom react js lib. when running this lib locally with a next js sample project i am getting

../src/components/Calendar/CalendarSelector.js
Module parse failed: Unexpected token (230:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

enter image description here

Below is my project overall structure. I have also added webpack file.

enter image description here

Import the file in index.js sample next js project

import { MuiDynaTable } from '../../../src/index';

Webpack.config.js file

module.exports = {
    // Other webpack configuration...
    module: {
        rules: [
            {
                test: /.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }
            }
        ]
    }
};

rollup.config.mjs


import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import { terser } from 'rollup-plugin-terser';
import image from '@rollup/plugin-image'; // Import the image plugin

export default {
    input: 'src/index.js', // Update this path to your library's entry point
    output: {
        file: 'dist/bundle.js', // Update this path to your desired output file
        format: 'umd', // Universal Module Definition (UMD)
        name: 'mui-dynatable', // Name of your library (optional)
        globals: {
            react: 'React', // External dependencies (optional)
            'react-dom': 'ReactDOM'
        }
    },
    plugins: [
        babel({
            exclude: 'node_modules/**',
            babelHelpers: 'bundled' // Use 'bundled' for Rollup
        }),
        resolve(),
        commonjs({
            include: /node_modules/,
            extensions: ['.js', '.jsx'] // Include JSX files
        }),
        postcss({
            extract: true, // Extract CSS to a separate file
            modules: true // Enable CSS modules (optional)
        }),
        image(), // Add the image plugin
        terser() // Minify the bundle (optional)
    ],
    external: ['react', 'react-dom'] // Specify external dependencies (optional)
};

Next js project config


module.exports = {
    output: 'export',

    images: {
        unoptimized: true
    },

    webpack: (config, { isServer }) => {
        // Add SVG loader
        config.module.rules.push({
            test: /.svg$/,
            use: ['@svgr/webpack']
        });

        config.module.rules.push({
            test: /.js$/,
            exclude: /node_modules/,
            include: /node_modules/mui-dynatable/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react']
                }
            }
        });

        if (!isServer) {
            config.externals.push(/static/fonts/.*$/);
        }

        return config;
    }
};

Node TS: JWT token sign to verify authentication between client and backend question

Is it safe to generate a JWT token on server-side and to pass it in a sign-up request within the response JSON back to the client?

Currently I’m generating a JWT in the following way:

import express from "express";
import jwt from "jsonwebtoken";

const generateToken = (id: any, res: express.Response) => {
    const token = jwt.sign({ id }, process.env.JWT_SECRET as string, {
        expiresIn: "15d",
    });

    return token;
};

export default generateToken;

Which is being used by the following auth.controller:

import express from "express";
import User from "../models/user.model";
import bcrypt from "bcrypt";
import generateToken from "../utils/generateToken";

export const signup = async (req: express.Request, res: express.Response) => {
    try {
        const { username, password, email } = req.body;

        // Check if all fields are filled in and been sent
        if (!username || !password || !email) {
            return res
                .status(400)
                .json({ message: "Please fill in all fields" });
        }

        // Check if the user already exists
        const userCheck = await User.findOne({ username });

        if (userCheck) {
            return res.status(400).json({ message: "User already exists" });
        }

        // Check if the email already exists
        const emailCheck = await User.findOne({ email });

        if (emailCheck) {
            return res.status(400).json({ message: "Email already exists" });
        }

        // Hash the password
        const salt = await bcrypt.genSalt(12);
        const hashedPassword = await bcrypt.hash(password, salt);

        // Create a new user
        const newUser = new User({
            username,
            password: hashedPassword,
            email,
        });

        // Generate and send token
        if (newUser) {
            const token = generateToken(newUser._id, res);
            await newUser.save();

            return res.status(201).json({
                user: newUser,
                token: token,
            });
        } else {
            return res.status(500).json({ message: "Something went wrong" });
        }
    } catch (error) {
        console.log(`Error in signup controller: ${error}`);
        return res.status(500).json({ message: "Something went wrong" });
    }
};

As the code shows, I’m generating the JWT token and send it from the backend to the client within a response from a client post.

// Generate and send token
if (newUser) {
    const token = generateToken(newUser._id, res);
    await newUser.save();

    return res.status(201).json({
        user: newUser,
        token: token,
    });
} else {
    return res.status(500).json({ message: "Something went wrong" });
}

In the client it will be saved to redux local-storage.

auth:"{"session":{"signedIn":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY2MWE1Y2U5NjAzYWRhNTMzODA2YjVkZSIsImlhdCI6MTcxMzAwMzc1MywiZXhwIjoxNzE0Mjk5NzUzfQ.v23o2WIIz6bYqxpP_wwG5Q3DZgwXtdPX1pMAnGsDKs4"},"user":{"avatar":"https://via.placeholder.com/150","username":"test","email":"[email protected]","authority":"user"}}"locale:"{"currentLang":"en"}"_persist:"{"version":-1,"rehydrated":true}"

Question: Is this a safe enough way to store it within the local-storage or is the set-header way required?

Nodejs Socket.io v4 disconnection problem on 1000 connections with 100 subscription each

I am trying to create one application using nodejs socket.io with version 4.

I am using very simple script that is accepting a connection and send a JSON dummy ({“abc”:”abc”}) payload on an event(say ‘loaddata’ event) into a socket room which is created on event call(if it is not already created).

While benchmarking, if i try to make 1000 connections with 100 common subscription(100 rooms), then it starts giving disconnection error of few socket connections after few seconds.

Server(where socket code is running) Machine details : 8cpu,8Gb RAM.

After TOP command usage, it seems , CPU is over 100% when i shoot 1000 connections in a go with 100 subscription each.

is there some limitation in socket.io or i am doing some mistake or is this is the max limit for socket.io with this conn number. ?

//Server code : 


const app = require('express')();
const server = require('http').Server(app);
const {
    Server
} = require("socket.io");


const io = new Server(server, {
    path: '/abc',
    transports: ['websocket']
})

io.on('connection', async (socket) => {
    socket.emit('broadcast', `Welcome to StreamerIO `)
    socket.on('dataload', (data) => {
        socket.join('datafeed_' + data.token);
        sendFeed('datafeed_' + data.token);
    });
});

const sendFeed = (room) => {
    io.to(room).emit("getdata", {
        "abc": "abc"
    });
}

server.listen("7005", () => {
    console.log(`Socket Server listening on ${server.address().address}:${server.address().port}`);
});


//Client Code :

const io = require("socket.io-client");

const connectFeed = async (subscription, tokens_list) => {

    const socket = io('ws://localhost:7005/', {
        path: "/abc",
        transports: ['websocket']
    });
    socket.on("connect", () => {

        function subscribetoken() {
            if (socket.connected) {
                if (tokens_list && tokens_list.length) {
                    tokens_list.forEach(token => {
                        socket.emit("dataload", {
                            token: token
                        });
                    });
                }
            }
        }

        function pingpong() {
            socket.emit("3");
        }
        setTimeout(subscribetoken, 1000)
        setInterval(pingpong, 1000)
    });

    socket.on('getdata', function(message) {
        console.log("received data");
    });

}

const startBenchMarking = (connections, subscription, tokens_list) => {

    var runConnections = () => {
        for (let i = 1; i <= connections; i++) {
            connectFeed(subscription, tokens_list)
        }
    }
    runConnections();

}
const NO_OF_CONNECTIONS = 1000;
const NO_OF_SUBSCRIPTIONS = 100;
const activetokens = ["a|1", "a|2", "a|3", ........] // an array of 100 diff tokens. 
startBenchMarking(NO_OF_CONNECTIONS, NO_OF_SUBSCRIPTIONS, activetokens);

i tried running above scripts with diff no of connections. it is running fine with upto 950 connections. and getting disconnections problem when connections crosses 1000+.

expecting : is there some limitation in socket.io or i am doing some mistake or is this is the max limit for socket.io with this conn number. ?

How to prevent react native modal from moving up when keyboard opens in ios?

I tried to stabilise the modal, but when i touch the screen the modal goes upward and breaking down the style.

<Modal modalVisible={props.visibility} onClose={() => props.onclose()} avoidKeyboard={false}>

<KeyboardAvoidingView
behavior={Platform.OS === ‘ios’ ? ‘padding’ : null`
style={{ flex: 1 }}
>

  <Loading loading={loading} />
  <Card containerStyle={styles.card}>
    <Text
      style={{
        color: colors.primaryColor,
        fontSize: 18,
        ...globalFonts.semiBold,
      }}>
      {t('ewallet_fund_transfer')}
    </Text>

    <InputItem
      required
      title={values[TRANSFER_TO]?.title}
      value={values[TRANSFER_TO].value}
      errorMessage={values[TRANSFER_TO].error}
      onchange={text => {
        handleChange(TRANSFER_TO, text);
      }}
      style={styles.inputItemStyle}
      inputContainerStyle={styles.inputContainerStyle}
    />
    <InputItem
      currency
      keyboardType="decimal-pad"
      title={values[AMOUNT].title}
      value={values[AMOUNT].value}
      errorMessage={values[AMOUNT].error}
      onchange={text => {
        handleChange(AMOUNT, text);
      }}
      style={styles.inputItemStyle}
      inputContainerStyle={styles.inputContainerStyle}
    />
    <InputItem
      currency
      editable={false}
      disabledStyle={styles.disableStyle}
      title={values[AVAILABLE_AMOUNT]?.title}
      value={values[AVAILABLE_AMOUNT].value}
      errorMessage={values[AVAILABLE_AMOUNT].error}
      onchange={text => {
        handleChange(AVAILABLE_AMOUNT, text);
      }}
      style={styles.inputItemStyle}
      inputContainerStyle={styles.inputContainerStyle}
    />

    <InputItem
      required
      secureTextEntry
      title={values[TRANS_PASSWORD]?.title}
      value={values[TRANS_PASSWORD].value}
      errorMessage={values[TRANS_PASSWORD].error}
      onchange={text => {
        handleChange(TRANS_PASSWORD, text);
      }}
      style={styles.inputItemStyle}
      inputContainerStyle={styles.inputContainerStyle}
    />

    <Button
      title={t('submit')}`your text`
      buttonStyle={{
        backgroundColor: colors.primaryColor,
        marginTop: 10,
      }}
      onPress={() => submitHandler()}
    />
  </Card>

`this is my code and i cant able to understand where i made mistake`