Problems with classes in Tailwind when mapping

I have an API that pulls all data from a table into one. The issue is that I have a Header Component with links, and to make it more flexible and dynamic, I want to separate the pages that have the same category as the link and map them into objects, filtering them. All the mapping goes very smoothly, however when I try to apply the Tailwind classes to them, in case the link they redirect to is the current one, for some reason it adds several commas at the end of the classes “,,,,”.

I’m using NextJS App Directory and Tailwind. Here is the code I used in the Header:

<li
          className={`h-full flex flex-col justify-center group items-center cursor-pointer text-[17px] text-[gray] hover:text-[hsl(var(--theme-color-light))] px-2 border-4 border-transparent ${pages
            .filter((p) => p.category === "8")
            .map((p) =>
              pathname === "/paginas/" + p.url
                ? "font-bold text-[hsl(var(--theme-color))] border-t-[hsl(var(--theme-color))]"
                : ""
            )}`}
        >
          HABBLETXD
          <ul className="absolute rounded-[0.3rem] shadow-[0px_0px_20px_hsla(0,0%,0%,0.25)] top-[65px] opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-all before:content-[''] before:w-0 before:h-0 before:absolute before:border-[7.5px] before:border-transparent before:border-b-[hsl(var(--theme-color))] before:top-[-15px] before:left-[calc(50%-10px)]">
            <div className="h-full w-full flex flex-col rounded-[0.3rem] overflow-hidden">
              {pages
                .filter((p) => p.category === "8")
                .map((item) => (
                  <a
                    className="px-4 py-[0.9rem] h-full w-full bg-white flex justify-center items-center text-base font-bold text-[hsl(var(--theme-color))] transition-all hover:bg-[hsl(var(--theme-color))] hover:text-white"
                    style={{ textShadow: "0px 0px 5px hsla(0, 0%, 0%, 0.25)" }}
                    key={item.name}
                    href={`/paginas/${item.url}`}
                  >
                    {item.name}
                  </a>
                ))}
            </div>
          </ul>
        </li>

The data I used in this code I set in states. In addition, I used hooks from NextJS itself, such as usePathname (pathname).

Here’s the print of how the code results:

How to reset `top`, `left`, `transition` attributes using a css class?

The below is meant for simulating a drag and drop effect. I’m manually changing the styles both on mousedown and mouseup events using Object.assign(target.style, ...). If I replace the assigment statements with .dragging class that contains the mousedown styles, followed by removing that class on mouseup, the associated left and top attributes set in mouseup stay after removing the .dragging class.

Here’s the working version:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                Object.assign(target.style, {
                    transition: null,
                    zIndex: 10000,
                    position: 'relative'
                });
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            Object.assign(target.style, {
                transition: 'all 0.5s ease',
                zIndex: null,
                left:  '0',
                top: '0'
            });
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto', sans-serif
}

.draggable {
  display: flex;
  padding: 10px 12px;
  margin-top: 0px;
  margin-left: 0px;
  margin-bottom: 11px;
  border-radius: 5px;
  margin-right: 5px;
  background-color: #000000;
  cursor: grab;
  flex-grow: 1;
  color: #ffffff;
  border: 1px solid #6c757d;
}

.my-card-group {
  margin-top: 30px;
  background-color: #000000;
  margin-right: 2%;
  margin-left: 2%;
  border: 1px solid #6c757d;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

Here’s what I do to replace the Object.assign(...) statements with .dragging class:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                target.classList.add('dragging')  // replaced with this
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            target.classList.remove('dragging') // replaced with this
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
 

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif
}

.draggable {
    display: flex;
    padding: 10px 12px;
    border-radius: 5px;
    margin: 0 5px 11px 0;
    background-color: #000000;
    cursor: grab;
    flex-grow: 1;
    color: #ffffff;
    border: 1px solid #6c757d;
    transition: all 0.5s ease; /*added this*/
    z-index: unset; /*added this*/
    left: 0; /*added this*/
    top: 0 /*added this*/
}

.dragging { /*added this*/
    z-index: 10000;
    position: relative;
    transition: all 0s;
}

.my-card-group {
    margin-top: 30px;
    background-color: #000000;
    margin-right: 2%;
    margin-left: 2%;
    border: 1px solid #6c757d;
}
 
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

This breaks how the dragging works because left and top as well as transition attributes persist after .dragging is removed, and the next time any of the .draggable is dragged, it starts where its previous drag ended and with a transition delay set by .dragging. Is there a way to achieve the initial behavior using a similar approach?

How to show a message if the search doesn’t match the result?

I am using node js and templates of ejs in my application, and I am trying to show a message in case the search field doesn’t match any result, I expected it will show me “Line does not exist.”, but it shows the search results instead as shown in the screenshot below:

enter image description here

I tried to modify the condition in the if statement <% } else if(oneresult != ''){ %> in different ways but it doesn’t work. Below is the code:

<%- include('partials/header') -%>

<div class="container mt-5 w-50">
  <h2 class="mb-4">Search a Line</h2>

  <form action="/line" method="GET">
    <input
      type="text"
      name="line"
      class="form-control"
      placeholder="Enter a Line"
    />

    <button type="submit" class="btn btn-danger btn-block mt-3">
      Search in Database
    </button>
  </form>

  <% if(oneresult) { %>
  <h4 class="text-danger my-4">Search Results:</h4>
  <table class="table table-bordered" width="100%" cellspacing="0">
    <thead>
      <tr>
        <th>ID</th>
        <th>Line</th>
        <th>Date</th>
      </tr>
    </thead>

    <tbody>
      <% oneresult.forEach( oneresult=>{ %>
      <tr>
        <td><%= oneresult.id %></td>
        <td><%= oneresult.result %></td>
        <td><%= oneresult.date %></td>
      </tr>
      <% }) %>
    </tbody>
  </table>
  <% } else if(oneresult != ''){ %>

  <div class="alert alert-danger mt-4">Line does not exist.</div>

  <% } %>
</div>

<%- include('partials/footer') -%>

Any suggestions, please?

Adding the onclick event to a field of each row in the Ajax datatables in HTML

I have a datatables table that uses JSON data to display information in the table.
I put the desired link along with its ID on one of the fields of each row so that the user can enter the page specific to the details of each field .
But now, instead of using the a tag, I want to create an onclick event that will open a web page for me by calling window.open(‘https://somewhere’).
I want to set an event on the data that comes from the title
I did a short search on the internet but did not find any results
Thank you for your help

The general form of codes related to the table and table script

table structure :

<table class="datatables-basic table table-bordered">
            <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th>schoolName</th>
                    <th>HeadName</th>
                    <th>PhoneNumber</th>
                    <th>HeadPhoneNumber</th>
                    <th>Address</th>
                    <th>IsActive</th>
                    <th>DO</th>

                </tr>
            </thead>
 </table>

table script (DataTable):

 $(function () {

            var dt_basic_table = $('.datatables-basic'),
                dt_basic;

            // DataTable with buttons
            // --------------------------------------------------------------------

            if (dt_basic_table.length) {
                var listFilesUrl = "https://localhost:44309/AllSchools";
                dt_basic = dt_basic_table.DataTable({
                    ajax: listFilesUrl,
                    columns: [
                        { data: '' },
                        { data: 'schoolId' },
                        { data: 'schoolId' },

                        //I want to set an event on the data that comes from the title
                        { data: 'title',
                            render: function (data, type, row) {
                                return $('<a>')
                                    .attr({ target: "_blank", href:"https://localhost:44309/RenderSchool?schoolId=" + row.schoolId })
                                    .text(data)
                                    .wrap('<div></div>')
                                    .parent()
                                    .html();
                            }
                        },

                        { data: null,
                            render: function (data, type, row){
                                var details = row.headFirstName + " " + row.headLastName;
                                return details;
                            }
                        },
                        { data: 'phoneNumber' },
                        { data: 'headPhoneNumber' },
                        { data: 'address' },
                        { data: 'isActive' },
                        { data: '' }
                    ],

Passing variables from view to Javascript code in Django

I have a template like the below in Django

{% extends 'reports/base.html' %}

{% block title %} Report Name {% endblock %}

{% block content %}
<!--
<div class="container-fluid">
  <div class="row"><div class="col">
    <ul class="list-group">
      {% for r in report_list %}
      <li class="list-group-item"><a class="link-offset-2 link-underline link-underline-opacity-0" href={% url 'reports' report_id=r.id %}>{{ r.report_name }}</a></a></li>
      {% endfor %}
    </ul>

  </div><div class="col"></div><div class="col"></div></div>
</div>-->
<div class="demo-container">
  <div id="sales"></div>
  <div id="sales-popup"></div>
</div>

<script>
  $(() => {
    let drillDownDataSource = {};
  
    $('#sales').dxPivotGrid({
      allowSortingBySummary: true,
      allowSorting: true,
      allowFiltering: true,
      allowExpandAll: true,
      showBorders: true,
      showRowGrandTotals: false,
      showColumnGrandTotals: false,
      fieldChooser: {
        enabled: true,
      },
      export: {
        enabled:true
        },
      onCellClick(e) {
        if (e.area === 'data') {
          const pivotGridDataSource = e.component.getDataSource();
          const rowPathLength = e.cell.rowPath.length;
          const rowPathName = e.cell.rowPath[rowPathLength - 1];
          const popupTitle = `${rowPathName || 'Total'} Drill Down Data`;
  
          drillDownDataSource = pivotGridDataSource.createDrillDownDataSource(e.cell);
          salesPopup.option('title', popupTitle);
          salesPopup.show();
        }
      },
      onExporting: function(e) { 
        var workbook = new ExcelJS.Workbook(); 
        var worksheet = workbook.addWorksheet('Main sheet'); 
        DevExpress.excelExporter.exportPivotGrid({ 
            worksheet: worksheet, 
            component: e.component,
            customizeCell: function(options) {
                var excelCell = options;
                excelCell.font = { name: 'Arial', size: 12 };
                excelCell.alignment = { horizontal: 'left' };
            } 
        }).then(function() {
            workbook.xlsx.writeBuffer().then(function(buffer) { 
                saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'PivotGrid.xlsx'); 
            }); 
        }); 
        e.cancel = true; 
    },
      dataSource: {
        fields: [
          /*{
          caption: 'primary_label',
          width: 120,
          dataField: 'primary_label',
          area: 'row',
        }, */{
          'caption': 'secondary_label',
          'dataField': 'secondary_label',
          'width': 150,
          'area': 'row',
          'expanded': true
        },
        {
          caption: 'account',
          dataField: 'account',
          width: 150,
          area: 'row',
          expanded: true
        },
        {
          caption: 'category',
          dataField: 'category',
          width: 150,
          area: 'row',
          expanded: true
        },
        {
          caption: 'subcategory',
          dataField: 'subcategory',
          width: 150,
          area: 'row',
          expanded: true
        }, {
          dataField: 'period',
          dataType: 'date',
          area: 'column',
        }, {
          caption: 'value_eth',
          dataField: 'value_eth',
          dataType: 'number',
          summaryType: 'sum',
          //format: 'Number',
          format: {
                type: "fixedPoint",
                precision: 0
            },
          area: 'data',
        },
      // Filters
        {
          area: 'filter', 
          dataField: 'secondary_label',
          filterType: 'include',
          filterValues: ['1.1. Staked Assets', '3.2. Operating Performance']
      },
      {
        area: 'filter', 
        dataField: 'account',
        filterType: 'include',
        filterValues: ['3.2.1. Net Revenue', '3.2.2. Cost of Revenue','1.1.1. Staked ETH']
    }],
        store: sales,
      },
    });
  
    const salesPopup = $('#sales-popup').dxPopup({
      width: 1360,
      height: 600,
      //resizeEnabled:true,
      contentTemplate(contentElement) {
        $('<div />')
          .addClass('drill-down')
          .dxDataGrid({
            width: 1260,
            height: 500,
            scrolling: {
              mode: 'virtual',
            },
            export: {
              enabled:true,
              allowExportSelectedData: true
              },
              onExporting(e) {
                const workbook = new ExcelJS.Workbook();
                const worksheet = workbook.addWorksheet('LIDO');
          
                DevExpress.excelExporter.exportDataGrid({
                  component: e.component,
                  worksheet,
                  autoFilterEnabled: true,
                }).then(() => {
                  workbook.xlsx.writeBuffer().then((buffer) => {
                    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'LIDO.xlsx');
                  });
                });
                e.cancel = true;
              },
            columns: ['period', 'primary_label', 'secondary_label', 'account','base_token_address','value_eth'],
          })
          .appendTo(contentElement);
      },
      onShowing() {
        $('.drill-down')
          .dxDataGrid('instance')
          .option('dataSource', drillDownDataSource);
      },
      onShown() {
        $('.drill-down')
          .dxDataGrid('instance')
          .updateDimensions();
      },
          
    }).dxPopup('instance');
  });
  
</script>
{% endblock %}

The portion where the field list definition starts, I wanted to make this dynamic and get the values from a view which has logic to determine the field list.

dataSource: {
        fields: [

Have the following on the view logic

    field_list = ['col1','col2']
    return render(request, 'reports/report.html', context={'field_list': field_list})

I tried using the Jinja expression within the javascript and it throws syntax error, how can I fix this.

      dataSource: {
        fields: [
        {% for f in field_list %}  
        {
          'caption': f,
          'dataField': f,
          'width': 150,
          'area': 'row',
          'expanded': true
        },
        {% endfor %}

Loading image from a website and displaying it onto a canvas

I am trying to build a frontend with SvelteKit which queries a webserver using an HTTP get request for a file. I receive the file (which is ZIP format), unzip it, and extract an image from it. I am trying to then display the image on the frontend, but am struggling to get the displaying part part working. I am new to Svelte, JS and frontend development (coming from a scientific programming/Python background) so I am trying to hack my way through this. This is what I’ve tried so far:

<script>
...
async function download() {
    ...
    // get image portion of the data
    const image_data = await zip_data.file('view_img.jpg').async('blob');

    image_url = URL.createObjectURL(image_data);
    console.log('image url', image_url);
    console.log(image_data)

    const ctx = canvas.getContext('2d');

    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    };
    img.src = image_url
}
</script>
...
<canvas bind:this={canvas} width=600 height=400></canvas>

VSCode is complaining that I cannot create the image object without any arguments (The error is showing up as: Expected 1 arguments, but got 0.js(2554)) but all of the code samples that I see online show Image being created with no arguments. The only difference I notice is that most of the code samples create images in the onMount() function, but in my specific case, I am trying to load an image after processing some user input and running my HTTP GET query.

I would appreciate someone’s help in figuring out how to do this seemingly simple task of downloading an image and showing it on the frontend that I’m building.

TYVM!

How can I treat special characters as part of a whole word in a regex search?

If I want to do a “whole word” search for a string with special characters, like say “A+”, how can I write a Javascript regex that will match the whole word for cases like the following:

  1. Is the only text in the string: “A+”
  1. Is at the end of the string: “You got an A+.”

  2. Is at the beginning of the string: “A+ good job!”

  3. Is in the middle: “You did A+ work here.”

It should return false for:

  1. Not whole word: “A++”

  2. Not whole word”: “You got an A++!”

… and many other cases

I’d love to just use b:

 /b(A+)b/g 

…but that seems to interact poorly with special characters (in fact I’m not sure that regex can even match anything…).

How can I determine if there is a duplicate dictionary in an array of dictionaries in JavaScript?

I have an array of dictionaries and I want to determine if there are any duplicate dictionaries. I tried using the _uniq method from Lodash.js and it looks like it’s finding unique dictionary objects but not determining if they’re equal. I also tried using the Set method which lets me store unique values of any type, whether primitive values or object references.

I know Lodash.js also has a method _.isEqual that determines equality between two unique dictionary objecs so it may be useful.

How can I determine if there is a duplicate dictionary in an array of dictionaries in JavaScript?

// The function should return True because there are two equal dictionaries
arr = [
    {
      "a": 1,
      "b": 2,
    },
    {
      "a": 1,
      "b": 2,
    }
];

// Lodash.js attempt
function hasDuplicate(arr) {
    return _uniq.(arr).length !== arr.length;
}

// Set attempt
function hasDuplicate(arr) {
    const noDuplicates = new Set(arr);
    return arr.length !== noDuplicates.size;
}

Unable to fetch data from database using Nodejs

I am working with Nodejs and using expressjs for API’S,Right now i am getting “undefined” in console.log (coming from model), How can i fetch data using express js ?

const sendotps = async (req, res) => {
    var phone_number=req.body.phone_number;
    if (!phone_number || !phone_number.trim() || phone_number == null || phone_number < 10)
        return res.status(400).send({ statusCode: 400, statusMessage: 'Bad Request', message: 'Enter valid mobile number', data: null });
    try {
        const result= await User.sendOtp(phone_number);
        console.log('result is '+ result);
        if(result!"notexist")
            {
                    // further code
            }
        else
            {
                    // further code
            }   
    } catch (err) {
        res.status(500).send({
            statusCode: 500,
            statusMessage: 'Internal Server Error',
            message: null,
            data: null,
        });
    }

Here is my “model file”(user.model)

static sendOtp(phone_number) {
        const sql2 = "SELECT * FROM users WHERE phone_number = '${phone_number}' AND is_registered='1'";
                const [rows2, fields2] = await pool.execute(sql2);
               if(rows2>0)
                {
                        return rows2;
                }
                else
                {
                        return "notexist";
                }
    } 

why js function works only when I run it with the debugger?

I have a javascript code and in this code I send an axios request to get the user whose password he entered belongs to him.
the problem is:
When I debug the code in the browser debug tool(f12), the code works fine, but if I don’t debug the code, the user login page refreshes again and again and there is no transition to the requested page.
what could be the problem? After all, it seems that the code is correct because when there is debugging it works…

The interesting thing is that in the first few runs of the function, the function worked fine even without the debugger, but only after a few times of running the function, the problems started as I mentioned above.

I would appreciate your help, thanks

**here is the js code:
**

function getPsd() {
    sessionStorage.login = null;
    var psd = document.getElementById("password").value;
    var fullPath = 'https://localhost:44371/api/Users/Get/?psd=';
    return axios.get(fullPath + psd).then(
        (response) => {
            var result = response.data;
            if (result != null) {
                sessionStorage.login = JSON.stringify(result);
                window.location.href = '../HomePage/HomelPage.html'
            }
            return result;
        }).catch((error) => {
            alert("erorr details")
            return null;
        });
}

**html code:
**

<body dir="rtl">
    <div class="login-container">
        <section class="login" id="login">
            <header>
               
                <h4>user login</h4>
            </header>
            <form class="login-form">
                <input type="text" id="userName" class="login-input" placeholder="User" required autofocus />
                <input type="password" id="password" class="login-input" placeholder="Password" required />
                <div class="submit-container">
                    <button onclick="getPsd()" class="login-button">היכנס</button>
                </div>
            </form>
        </section>
    </div>
</body>

I tried to search for any relevant solution but i didn’t find nothing…

Vue 3 Compositions api not auto reloading when there’s a changes

I’m currently taking a lesson in vue mastery. and there’s a weird behavior. when I’m changing something in the App.vue it is auto reloading and showing my changes. But when I’m changing something in the component files, it is not auto reloading. i just follow the documentation on how to setup a vue 3 application

App.Vue

<script setup>
import ProductDisplay from '@/Components/ProductDisplay.vue'
import { ref } from 'vue'

 const cart = ref(0)
 const premium = ref(true)
</script>
<template>

<div class="nav-bar"></div>
<div class="cart">{{ cart }}</div>
<ProductDisplay :premium="premium" />

</template>

Components/ProductDisplay.vue

<script setup>
import { ref, computed } from "vue";
import socksGreen from "@/assets/images/socks_green.jpeg";
import socksBlue from "@/assets/images/socks_blue.jpeg";

const props = defineProps({
  premium: Boolean,
 });

 const details = ref(["50% cotton", "30% wool", "20% polyster"]);

 const variants = ref([
   { id: 2234, color: "green", image: socksGreen, quantity: 50 },
   { id: 2235, color: "blue", image: socksBlue, quantity: 0 },
 ]);

 const inStock = computed(() => {
   return variants.value[selectedVariants.value].quantity > 0;
 });
 const selectedVariants = ref(0);

 const cart = ref(0);

 const onClick = () => {
   cart.value += 1;
 };

 const image = computed(() => {
   return variants.value[selectedVariants.value].image;
 });
const updateVariant = (index) => {
  selectedVariants.value = index;
};

const shipping = computed(() => {
  if (props.premium) {
    return "Frees"
  } else {
    return "Out of Stock";
  }
});
</script>

<template>
 <div class="product-display">
   <div class="product-container">
     <div class="product-image">
       <img :src="image" alt="" />
     </div>
     <div class="product-info">
       <h1>{{ product }}</h1>
       <p v-if="inStock">In Stock</p>
       <p v-else>Out of Stock</p>
       <p>{{ shipping }}</p>
       <ul>
         <li v-for="detail in details">{{ detail }}</li>
       </ul>
      <div
        class="color-circle"
        v-for="(variant, i) in variants"
        :style="{ backgroundColor: variant.color }"
        @mouseover="updateVariant(i)"
      ></div>
      <button
        :class="{ disabledButton: !inStock }"
        class="button"
        @click="onClick"
        :disabled="!inStock"
      >
        Add to Cart
      </button>
     </div>
   </div>
  </div>
 </template>

How do I resolve Invalid Hook call error in React when trying to use route/navigate

I’m working on a project currently and keep getting this error with my routing:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (react-dom.development.js:16227:1)
    at Object.useContext (react.development.js:1618:1)
    at useInRouterContext (hooks.tsx:85:1)
    at Navigate (components.tsx:196:1)
    at Login.jsx:24:1

This is the components of the app that I’ve got coded:

import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import { Navigate } from "react-router-dom";

const Login = () => {
  const location = useLocation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const submitForm = (event) => {
    event.preventDefault();
    fetch("http://localhost:8000/users")
      .then((response) => response.json())
      .then((data) => {
        const user = data.find(
          (user) =>
            user.email &&
            user.email.toLowerCase() === email.toLowerCase() &&
            user.password &&
            user.password.toLowerCase() === password.toLowerCase()
        );
        if (user) {
          Navigate("/profile");
        } else {
          setErrorMessage("Invalid email or password");
        }
      })
      .catch((error) => console.log(error));
  };

  return (
    <div>
      <form onSubmit={submitForm}>
        <div>
          <label htmlFor="email">Enter Email Address:</label>
          <input
            type="text"
            name="email"
            id="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="password">Enter Password:</label>
          <input
            type="password"
            name="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <button type="submit">Login</button>
      </form>
      {errorMessage && <p>{errorMessage}</p>}
    </div>
  );
};

export default Login;

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Profile from "./components/Profile";
import Login from "./components/Login";

function App() {
  return (
    <div className="wrapper">
      <h1>Application</h1>
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

import React from "react";


const Profile = () => {
  return (
    <div>
      <h2>Dashboard</h2>
      <p>Welcome to your profile page!</p>
      {/* Display user profile information here */}
    </div>
  );
};

export default Profile;

I’ve tried several fixes, such as reinstalling VSCode/Node.js, starting a new React app, using npm link ../myapp/node_modules/react… Most fixes I could find in the last 24 hours.

This is my current react versions:

PS C:UsersAdminDocumentsSD Semester2Final_Sprintfinalsprint> npm ls react
[email protected] C:UsersAdminDocumentsSD Semester2Final_Sprintfinalsprint
├─┬ @testing-library/[email protected]
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
└── [email protected]

Also, when I try and see the react version on my browser console with React.version, it says that React is not defined.

Binary array present in response is being converted to string in react

Hi I am using axios to make backend api calls. My response object which is generated using Java has following structure

 {
      workbook: [] //array of binary data of excel file generated using apache poi
      userId:<userId>
      
   }

When I receive the response given by axios , ‘workbook’ property which is supposed to be byte array is coming as string. I am not sure if axios is converting the byte array to string. Can someone tell me What is the correct way of dealing with byte data in axios