emotion style priority issue help me

[[enter image description here](https://i.sstatic.net/MBvjZmpB.png)](https://i.sstatic.net/15xfNv3L.png)

After creating a component and ordering the npm package by specifying the emotion style like this

When using that component in another project, the css attribute is used to specify the style, but if you want to overwrite the same style attribute, it is pushed out of style priority and does not apply.

Isn’t it a priority to apply the style with in-line properties?

And if you try to overwrite the style using the css attribute in another project, the number of classes increases by one more to two

When you open dev in the repo that made the npm package and take the same action, the style is applied and there is 1 class.

How to get TRUE / FALSE or CHECKED / UNCHECKED or 1 / 0 from html checkbox

I am tring to get the state of the checkbox from an html table in javascript so I can then use it to edit information on the following page, and then save to mysql database.

When I click on the edit button it runs the following script and then go to the edit page where I need a 1 or 0 depending on the checkbox state to carry over, but it does not or at least in the format I need.

Using javascript Alert(); it displays the entire html input line code with checked=’checked’ at the end. When I click the edit button on a record in the html table that has the checkbox set in the database.

How can I get what I need?

here is the script code.

<script>
function editsubcategory(element, value) {
    var _$index = (element.parentNode.parentNode.rowIndex)
    var myTab = document.getElementById('subcategorytable');
    var objCells = myTab.rows.item(element.parentNode.parentNode.rowIndex).cells;
    var _$subCategoryID = objCells.item(0).innerHTML; // categoryID
    var _$subCategoryName = objCells.item(1).innerHTML; // categoryName
    var _$subCategoryDescription = objCells.item(2).innerHTML; // categoryDescription
    var _$subCategoryMain = objCells.item(3).innerHTML; // subCategoryMain
    var _$subCategoryType = objCells.item(4).innerHTML; // subCategoryType
    var _$subCategoryBudget = objCells.item(5).innerHTML; // subCategoryType
    var _$subCategoryDiscretionary = objCells.item(6).innerHTML; // subCategoryType


    var _$btn = value; // button

    // alert(_$subCategoryID);
    // alert(_$subCategoryName);
    // alert(_$subCategoryDescription);
    // alert(_$subCategoryMain);
    // alert(_$subCategoryType);
    // alert(_$subCategoryBudget);
    // alert(_$subCategoryAccount);
    alert(_$subCategoryDiscretionary);
    // alert(_$btn);

    window.location.href = "edit-subcategory.php?subCategoryID=" + _$subCategoryID
+ "&btn=" + _$btn
+ "&subCategoryName=" + _$subCategoryName
+ "&subCategoryDescription=" + _$subCategoryDescription
+ "&subCategoryMain=" + _$subCategoryMain
+ "&subCategoryType=" + _$subCategoryType
+ "&subCategoryBudget=" + _$subCategoryBudget
+ "&subCategoryDiscretionary=" + _$subCategoryDiscretionary;

};
</script>

I have tried different ways to get the state, but nothing has worked. I think the issue is with what is being returned from the
var _$subCategoryDiscretionary = objCells.item(6).innerHTML;
line but I have no idea how to get the state.

This 6th item contains a checkbox.

I just want the variable _$subCategoryDiscretionary to be either a 1 or 0, true or false, checked or unchecked so i can perform an IF statement on it.

Oracle APEX validation in interactive grid

I am trying to validate two date columns in interactive grid with Javascript and use of DA.

I am currently “stuck” at a point where the code works, but it also doesn’t. What it’s supposed to do, is to check two date columns if the e.g. departure date is later than arrival date. If the departure date is earlier than arrival date, then it should return an error that the date is incorrect. Now I can freely pick an incorrect departure date and save it, but when I go and edit the departure date and change the date, that’s when the error pops up. I think there’s an issue with validation because in the console I can see that the function is being called but the log for checking record only registers arrival date being picked but not departure, where the validation should be made.

There’s no actual error. The “error” is that when I first add the date, I can save it without a problem, even if the date is INCORRECT console log (that’s when I should get a pop up message saying the date is incorrect). And then when I go and edit the date, I get a console log, that the previous date was recognized and that’s when the error pops up. As if the validation was delayed by one date

How could I fix that or does anyone know, where/what could the problem be?

function validateDate() {
    console.log("Validation function called");

    var regionStaticId = "my_ig";
    var grid;

    try {
        grid = apex.region(regionStaticId).widget().interactiveGrid("getViews", "grid");
    } catch (e) {
        console.error("Interactive grid not found.", e);
        return false;
    }

    var model = grid.model;
    var arrivalIdx = model.getFieldKey("Arrival");
    var departureIdx = model.getFieldKey("Departure");

    apex.message.clearErrors();

    var currentRecord = grid.view$.grid("getSelectedRecords")[0];

    if (currentRecord) {
        var arrival = currentRecord[arrivalIdx];
        var departure = currentRecord[departureIdx];

        console.log("Checking record: ", currentRecord);
        console.log("Arrival: ",arrival, "Departure: ",departure);

        if (arrival && departure) {
            var arrivalDate = new Date(arrival);
            var departureDate = new Date(departure);

            console.log("Arrival Date: ",arrivalDate, "Departure Date: ",departureDate);

            if (arrivalDate < departureDate) {
                console.log("Invalid date detected");

                apex.message.showErrors([{
                    type: "error",
                    location: "page",
                    message: "Pick a different date.",
                    pageItem: null
                }]);

                grid.view$.grid("gotoCell", {
                    row: model.getRecordId(currentRecord),
                    field: departureIdx
                });

                model.setValue(currentRecord, departureIdx, null);
                return false; 
            }
        }
    } else {
        console.error("No editable record selected.");
    }

    return true; 
}

$(document).ready(function() {
    $("input[name=fo6]").on("change", function(event) {
        if (!validateDate()) {
            event.preventDefault();
        }
    });
});

IN DYNAMIC ACTION I CALL THE FUNCTION ABOVE

how would you validate and display password using javascript simply?

i want to take password and be sure they are compatible with the characters in the password input and turn the text green when valid

pass.onfocus = function() {
  msg.style.display = 'block'
}
pass.onblur = function() {
  msg.style.display = 'none'
}
pass.onkeyup = function() {
  if (pass.match(lowerCase)) {
    letter.classList.remove('invalid');
    letter.classList.add('valid');

  } else {
    letter.classList.remove('vaild');
    letter.classList.add('invalid');
  }

  if (pass.match(capitalLetters)) {
    capital.classList.remove('valid');
    capital.classList.add('invalid');
  } else {
    capital.classList.remove('invalid');
    capital.classList.add('valid');
  }

i tried turning the text for the rules to vaild and green but i want it to display at the same time

Adding buttons to the dialog header

I want to add two buttons to a dialog header in my Oracle APEX application.

  1. One would go just to the left of the button that closes the dialog with a little bit of padding between the two. Extra credit for enlarging the “dialog close” button so that it is the same size as the button added

  2. The second button would go in the top right corner of the dialog page

In other words one button before the ui-dialog-title element and one button after it. I have some javascript code I found that will place a button to the right of the window close:

$('.ui-dialog-titlebar', window.parent.document).append('<button type="button" class="t-Button">Button Name</button>');

$('.someIdentifier', window.parent.document).click(function(){

    console.log('button is clicked');

});

By changing the .ui-dialog-titlebar parameter you can change which element to place the button immediately after but I feel that a function that places html code immediately before an element rather than appending it would help solve my problem.

JavaScript – Organize an array of objects by due_date property into its own array [duplicate]

I have an array of objects that I want to organize by the due_date property and put them into their own array. In the end I would have an array of arrays and each array would have an object where the due dates match.

For example, this is the data I’m getting:

[
    {
        task: 1,
        id: 748349238042,
        due_date: "2024-05-17"
    },
    {
        task: 2,
        id: 74374329823,
        due_date: null
    },
    {
        task: 3,
        id: 4379437297132,
        due_date: "2024-05-17"
    },
    {
        task: 4,
        id: 748349238042,
        due_date: "2024-06-03"
    },
    {
        task: 5,
        id: 789329779012,
        due_date: "2024-05-17"
    },
]

and what I would like it to look like is this:

[
    [
        {
            task: 1,
            id: 748349238042,
            due_date: "2024-05-17"
        },
        {
            task: 3,
            id: 4379437297132,
            due_date: "2024-05-17"
        },
        {
            task: 5,
            id: 789329779012,
            due_date: "2024-05-17"
        },
    ],
    [
        {
            task: 4,
            id: 748349238042,
            due_date: "2024-06-03"
        },
    ],
    [
        {
            task: 2,
            id: 74374329823,
            due_date: null
        },
    ]
]

So all the “2024-05-17” dates are in their own array and so is the “2024-06-03”, and any dates that are null are in their own array as well at the end. They don’t need to be sorted in any way in their own arrays either, I just need them together in their own array.

ApexCharts line graph always loads zoomed in, need to show all data on first load

I have an apex chart line graph with a y axis that spans from 2.5 – 5 and an x axis that spans from 0 – 5. There are many data points on the graph, like a thousand, but I want them all to show in a smooth line on initial load of the graph.

For some reason, when I first load the page, the graph always loads with only five ticks in the X axis, and changing the tickAmount doesn’t effect anything until I start zooming out.

Also, when the page first loads, the graph is zoomed in to the first five datapoints. I need to see every datapoint at once, and I can’t see them until I start zooming out.

If I set the stepSize to 1 (or don’t set it) then it shows the correct range, up to 5, but the lines on the graph still go way off screen even though they should only ever stop at 5!

Then, when I do zoom out, if I zoom out too quickly it completely destroys the x axis values and for some reason the numbers start going up into the hundreds or thousands even though xaxis.max is set to 5!

Changing the range also doesn’t do anything, unless I’m doing it wrong. From docs it looks like I have to set range to max - min?

I have also tried disabling zoom but it stays zoomed in to the first five out of 1,000 datapoints and then I can’t see the whole graph

What am I missing here, I’m following all the docs and it is acting so strangely

I want a user to be able to hover over the line and see the numerical value of the datapoint hover in the tool tip, for all 1000 data points, including between x-axis ticks

Here’s my options:

chartOptions() {
      return {
        chart: {
          type: 'line',
          height: 'auto',
          zoom: {
            enabled: true,
          },
        },
        dataLabels: {
          enabled: false
        },
        stroke: {
          curve: 'smooth'
        },
        title: {
          text: 'Line graph',
          align: 'left'
        },
        xaxis: {
          type: 'numeric',
          min: this.xMin,
          max: this.xMax,
          tickAmount: 5,
          // stepSize: .2,
          title: {
            text: 'x axis'
          },
        },
        yaxis: {
          show: true,
          min: this.yMin,
          max: this.yMax,
          tickAmount: 10,
          title: {
            text: 'y axis'
          },
          labels: {
            formatter: function (val) {
              return val.toFixed(2);
            }
          },
        }
      };
    },

How can I make sure my arrays have been updated when looping through them? [duplicate]

I’m running two Axios GET requests. After the first GET finishes, I loop through the response to simplify each returned object so it only contains what I need (data[i] within the first loop, below). From there I run a second GET to retrieve child data from the individual objects that I can’t access without another request, accessed by the “key” value (query2).

I then run a second loop to attach all the children objects retrieved from the second response and attach them iteratively to the parent object (data[i]).

The problem I’m having is that often (not always) the second loop throws a

TypeError: Cannot read properties of undefined (reading ‘episodes’)
at newAdditionCheck (…botplexTV.js:89:26)
at runMicrotasks ()
at processTicksAndRejections (node:internal/process/task_queues:96:5)

error at the data[i].episodes.push(data2[j]) point. When I log the different objects within the loop they exist as they should, so my only guess is some of the loops are finishing before others, but any input or fixes would be greatly appreciated. Thank you!

let baseURL1 = `http://${plexKeys.hostname}:${plexKeys.port}`;
let baseURL2 = `/?X-Plex-Token=${plexKeys.token}`;

const response = await axios({
  method: "GET",
  url: `${baseURL1}${query}${baseURL2}`,
});
let data = response.data.MediaContainer.Metadata;
for (i = 0; i < data.length; i++) {
  data[i] = {
    name: data[i].parentTitle,
    key: data[i].queryToken,
    episodes: [],
  };
  query2 = data[i].key;
  const response2 = await axios({
    method: "GET",
    url: `${baseURL1}${query2}${baseURL2}`,
  });
  let data2 = response2.data.MediaContainer.Metadata;
  for (let j in data2) {
    data2[j] = {
      series: data2[j].grandparentTitle,
      season: data2[j].parentTitle,
    };
    data[i].episodes.push(data2[j]);
  }
  continue;
}

File System Access API only working for .txt file extension

I am working on a Next.js application and I am using the File System Access API to prompt the user for a folder location and create a file at that location. I have a valid FileSystemDirectoryHandle but this fails when I call a getFileHandle function on it with any extension other than .txt. This piece of code has been working for 2 weeks now creating .ini files using the getFileHandle but this week I am getting errors that say:

desLoad failed:  TypeError: Failed to execute 'getFileHandle' on 'FileSystemDirectoryHandle': Name is not allowed.

Rewritting the code like this succeeds:

desTestHandle = await newBuildingHandle.getFileHandle('desload.txt', {
   create: true,
});

While this part fails and throws an error:

desTestHandle = await newBuildingHandle.getFileHandle('desload.ini', {
   create: true,
});

Thanks in advance for any insight anyone can provide on this cause I’m stumped!

How to use a CSS variable inside a custom HTML element?

I have a custom HTML element I made that creates a repeating background pattern which I animate in. I need the ability to dynamically set the color of this pattern with a CSS variable that lives in the parent/main document scope.

I know this is possible, but I think the complication is that I am setting the BG pattern as a CSS background image string.

customElements.define(
  'svg-background',
  class extends HTMLElement {
    connectedCallback() {
      setTimeout(() => {
        // wait till <template> is parsed as DOM
        let svg = this.querySelector('template')
          .innerHTML.replaceAll(/(ns*)|(<!-- .*? -->)/g, '') //remove linebreaks & indentations after linebreaks, and comments
          .replaceAll('"', "'") //replace double quotes
          .replaceAll('#', '%23'); //escape #
        Object.assign(this.style, {
          backgroundImage: `url("data:image/svg+xml;utf8,${svg}")`,
        });
      });
    }
  },
);

function toggleColor(){
  document.documentElement.classList.toggle('theme-blue')
}
:root{
  --hex-color: red;
}

:root.theme-blue{
  --hex-color: blue;
}

svg-background {
  position: fixed;
  bottom: 0;
  left:0;
  width: 100vw;
  height: 800px;
  transform: translateZ(0);
  pointer-events: none;
  z-index: -1;
}
<button type="button" onclick="toggleColor()">Toggle Color</button>

<svg-background>
  <template>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 90 800">
      <defs>
        <style>
          use {
            animation: 0.4s fade-in-hex;
            animation-fill-mode: both;
            fill: var(--app-theme-hex);
          }
          @keyframes fade-in-hex {
            from {opacity: 0;}
            to {opacity: 1;}
          }
          #hex-col use:nth-child(1) {animation-delay: 0.9s;}
          #hex-col use:nth-child(2) {animation-delay: 0.8s;}
          #hex-col use:nth-child(3) {animation-delay: 0.7s;}
          #hex-col use:nth-child(4) {animation-delay: 0.6s;}
          #hex-col use:nth-child(5) {animation-delay: 0.5s;}
          #hex-col use:nth-child(6) {animation-delay: 0.4s;}
          #hex-col use:nth-child(7) {animation-delay: 0.3s;}
          #hex-col use:nth-child(8) {animation-delay: 0.2s;}
          #hex-col use:nth-child(9) {animation-delay: 0.1s;}
        </style>
        <path id="hex" d="M0 25.980762113533157L15 0L45 0L60 25.980762113533157L45 51.96152422706631L15 51.96152422706631Z" />
      </defs>
      <!-- We repeat a pattern of 3 columns. One in the middle, and then two on either side that are cut in half so they line up when they meet -->
      <g id="hex-col">
        <use href="#hex" transform="translate(25 25) scale(.2)" />
        <use href="#hex" transform="translate(21 115) scale(.3)" />
        <use href="#hex" transform="translate(18 205) scale(.4)" />
        <use href="#hex" transform="translate(15 295) scale(.5)" />
        <use href="#hex" transform="translate(12 385) scale(.6)" />
        <use href="#hex" transform="translate(10 475) scale(.7)" />
        <use href="#hex" transform="translate(8 565) scale(.8)" />
        <use href="#hex" transform="translate(4 655) scale(.9)" />
        <use href="#hex" transform="translate(0 750)" />
      </g>
      <use href="#hex-col" transform="translate(45 -51)" />
      <use href="#hex-col" transform="translate(-45 -51)" />
    </svg>
  </template>
</svg-background>

Why am I unable to login to this admin panel?

I have set this logic that when the credentials and when the token is set properly a user can login. I am adding true credentials and the token is being retrieved from the backend successfully but I cant login. I suppose that when landing on /add page when the user has not logged in yet it displays login but I m unsure why the login is being displayed without the /add

// eslint-disable-next-line no-unused-vars
import React, { useState, useEffect } from 'react'
import Navbar from './components/Navbar'
import Sidebar from './components/Sidebar'
import { Routes, Route } from 'react-router-dom'
import Add from './pages/Add'
import List from './pages/List'
import Orders from './pages/Orders'
import Login from './components/Login'
import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'


export const backendUrl = 'http://localhost:5000'

const App = () => {
  const [token, setToken] = useState(localStorage.getItem('token') ? localStorage.getItem('token') : '')

  useEffect(() => {

    localStorage.setItem('token', token)

  }, [token])

  return (
    <div className='bg-gray-50 min-h-screen'>
      <ToastContainer />
      {token === "" ?
        <Login setToken={setToken} />
        :
        <>
          <Navbar setToken={setToken} />
          <hr className='orange-400' />
          <div className='flex w-full'>
            <Sidebar />
            <div className='w-[70%] mx-auto ml-[max(5vw,25px)] my-8 text-gray-700 text-base'>
              <Routes>
                <Route path='/Add' element={<Add token={token} />} />
                <Route path='/List' element={<List token={token} />} />
                <Route path='/Orders' element={<Orders token={token} />} />
              </Routes>
            </div>
          </div>
        </>
      }

    </div>
  )
}

export default App

and here is the Navbar.jsx

// eslint-disable-next-line no-unused-vars
import React, { useState, } from 'react';
import PropTypes from 'prop-types';// Import PropTypes
import { Card, Input, Button, Typography } from "@material-tailwind/react";
import { backendUrl } from '../App';
import { toast } from 'react-toastify';
import axios from 'axios';

const Login = ({ setToken }) => {
  const [telephone, setTelephone] = useState('');
  const [password, setPassword] = useState('');

  const onSubmitHandler = async (e) => {
    try {
      e.preventDefault();

      const response = await axios.post(`${backendUrl}/api/v1/auth/login`, {
        telephone,
        password,
      });
    

      if (response.data.success) {
        setToken(response.data.token);
      } else {
        toast.error(response.data.message);
      }
    } catch (error) {
      console.log(error);
      toast.error(error.message);
    }
  };

  return (
    <div className="flex justify-center items-center pt-10 min-h-screen">
      <Card color="transparent" shadow={false} className="border p-8 max-w-md w-full">
        <Typography variant="h4" className="text-center text-bold text-orange-400">
          Admin Panel Login
        </Typography>
        <Typography color="gray" className="mt-1 font-normal text-center">
          Enter your details to log in.
        </Typography>

        <form className="mt-8 mb-2 w-full max-w-xs mx-auto" onSubmit={onSubmitHandler}>
          <div className="mb-4 flex flex-col gap-6">
            <Typography variant="h6" color="blue-gray" className="-mb-3">
              Your Phone Number
            </Typography>
            <Input
              name="phoneNumber"
              type="tel"
              size="lg"
              placeholder="+250781947484"
              value={telephone}
              onChange={(e) => setTelephone(e.target.value.replace(/[^0-9+]/g, ''))}
              className="!border-t-blue-gray-200 focus:!border-t-orange-400"
              labelProps={{
                className: "before:content-none after:content-none",
              }}
            />

            <Typography variant="h6" color="blue-gray" className="-mb-3">
              Password
            </Typography>
            <Input
              name="password"
              type="password"
              size="lg"
              placeholder="********"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="!border-t-blue-gray-200 focus:!border-t-gray-900"
              labelProps={{
                className: "before:content-none after:content-none",
              }}
            />
          </div>

          <Button
            type="submit"
            className="mt-6 p-3 bg-orange-400 text-white hover:bg-orange-500"
            fullWidth
          >
            Log In
          </Button>
        </form>
      </Card>
    </div>
  );
};

Login.propTypes = {
  setToken: PropTypes.func.isRequired, // Expecting a function as the setToken prop
};

export default Login;

This image shows my response.body which also returns the token

Thank you for your help.

How can I securely store and validate JWT tokens in a React app to prevent automatic logins without explicit user providing credentials?

Even though I haven’t logged in, the app is still recognizing the stored token (if present in localStorage) and showing me as logged in. It seems like the token isn’t being cleared or revalidated properly, and I don’t want the user to be considered logged in until they actually submit their credentials and receive a valid token.

The image shows that I m returning the token in the body successfully and also I validated the token their so I don’t want to validate it on frontside

I have tried using useEffect but also automatically logs me in with no credentials provided

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types'; // Import PropTypes
import { Card, Input, Button, Typography } from "@material-tailwind/react";
import { backendUrl } from '../App';
import { toast } from 'react-toastify';
import axios from 'axios';

const Login = ({ setToken }) => {
  const [telephone, setTelephone] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async (e) => {
    try {
      e.preventDefault();

      const response = await axios.post(`${backendUrl}/api/v1/auth/login`, {
        telephone,
        password,
      });
      toast.success('Login successful!');

      if (response.data.success) {
        setToken(response.data.token); // Set token in state
        localStorage.setItem('token', response.data.token); // Store token in local storage
        console.log(response.data.token);
      } else {
        toast.error(response.data.message);
      }
    } catch (error) {
      console.log(error);
      toast.error(error.message);
    }
  };

  return (
    <div className="flex justify-center items-center pt-10 min-h-screen">
      <Card color="transparent" shadow={false} className="border p-8 max-w-md w-full">
        <Typography variant="h4" className="text-center text-bold text-orange-400">
          Admin Panel Login
        </Typography>
        <Typography color="gray" className="mt-1 font-normal text-center">
          Enter your details to log in.
        </Typography>

        <form className="mt-8 mb-2 w-full max-w-xs mx-auto" onSubmit={handleLogin}>
          <div className="mb-4 flex flex-col gap-6">
            <Typography variant="h6" color="blue-gray" className="-mb-3">
              Your Phone Number
            </Typography>
            <Input
              name="phoneNumber"
              type="tel"
              size="lg"
              placeholder="+250781947484"
              value={telephone}
              onChange={(e) => setTelephone(e.target.value.replace(/[^0-9+]/g, ''))}
              className="!border-t-blue-gray-200 focus:!border-t-orange-400"
              labelProps={{
                className: "before:content-none after:content-none",
              }}
            />

            <Typography variant="h6" color="blue-gray" className="-mb-3">
              Password
            </Typography>
            <Input
              name="password"
              type="password"
              size="lg"
              placeholder="********"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="!border-t-blue-gray-200 focus:!border-t-gray-900"
              labelProps={{
                className: "before:content-none after:content-none",
              }}
            />
          </div>

          <Button
            type="submit"
            className="mt-6 p-3 bg-orange-400 text-white hover:bg-orange-500"
            fullWidth
          >
            Log In
          </Button>
        </form>
      </Card>
    </div>
  );
};

Login.propTypes = {
  setToken: PropTypes.func.isRequired, // Expecting a function as the setToken prop
};

export default Login;

App.jsx

// eslint-disable-next-line no-unused-vars

import React, { useState } from 'react'
import Navbar from './components/Navbar'
import Sidebar from './components/Sidebar'
import { Routes, Route } from 'react-router-dom'
import Add from './pages/Add'
import List from './pages/List'
import Orders from './pages/Orders'
import Login from './components/Login'
import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'


export const backendUrl = 'http://localhost:5000'

const App = () => {
  const [token, setToken] = useState(null)

  return (
    <div className='bg-gray-50 min-h-screen'>
      <ToastContainer />
      {token === "" ?
        <Login setToken={setToken} />
        :
        <>
          <Navbar />
          <hr className='orange-400' />
          <div className='flex w-full'>
            <Sidebar />
            <div className='w-[70%] mx-auto ml-[max(5vw,25px)] my-8 text-gray-700 text-base'>
              <Routes>
                <Route path='/add' element={<Add />} />
                <Route path='/list' element={<List />} />
                <Route path='/orders' element={<Orders />} />
              </Routes>
            </div>
          </div>
        </>
      }

    </div>
  )
}

export default App

  

State Management for Real-Time Data Updates in React with TypeScript

I’m building a React application with TypeScript that processes real-time data streams. Using useState and useEffect causes excessive re-renders, impacting performance. How can I optimize state management for frequent updates, perhaps using Context, Redux, or another library?

What I tried:
I started by exploring TypeScript’s built-in utility types such as Partial, Omit, and Pick to create the desired nested type transformation. For example:

type NestedPartial<T> = {
    [K in keyof T]?: T[K] extends object ? NestedPartial<T[K]> : T[K];
};

I also experimented with conditional types and recursive mappings to handle deeply nested objects. For instance, I tried something like:

type TransformDeep<T> = T extends object 
    ? { [K in keyof T]: TransformDeep<T[K]> } 
    : T;

This approach worked well for constructing deeply nested structures but failed when I attempted to dynamically combine transformations (e.g., Partial and Readonly) based on specific conditions.

To troubleshoot, I attempted to create separate utility types for each transformation and then compose them. butt, this resulted in type errors or unexpected behavior due to how TypeScript evaluates deeply nested structures.


What I expected:
I expected to define a type that applies one or more transformations (such as Partial or Readonly) to all properties in a deeply nested structure, dynamically determined by runtime or type-level conditions. My goal was for TypeScript to infer the desired transformed structure without throwing errors or losing type safety.

For example:

type Input = {
    a: {
        b: {
            c: string;
            d: number;
        };
    };
    e: boolean;
};

type ExpectedOutput = {
    a?: {
        b?: {
            c?: string;
            d?: number;
        };
    };
    e?: boolean;
};

This is where I got stuck—how to dynamically combine transformations while ensuring TypeScript accurately infers deeply nested structures, all without requiring excessive boilerplate code.

I cant get my gsap animation to work on the way backup

I’ve been working on a website and have been trying to get my animation to work. Oddly enough it works when you click on it and it expands but it doesnt work when you click on it again which should shrink it. It does work when you shrink it if another foodCard is expanded and you’re shrinking a different foodCard. Does anyone know why this might be happening?

import React, { useEffect, useRef, useState } from 'react';
import Star from '../Star/Star';
import MacroTable from "../Macros/MacroTable";
import { FaLeaf, FaBreadSlice, FaHandRock } from 'react-icons/fa';
import gsap from "gsap";
import {useGSAP} from "@gsap/react";

function FoodCard({ foodItem, updateRating }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const cardRef = useRef(null);

  useEffect(() => {
    let tl = gsap.timeline();
    if (isExpanded) {
      gsap.to(cardRef.current, {
        height: 'auto',
        duration: 0.5,
        ease: 'linear'
      });
    } else {
      gsap.to(cardRef.current, {
        height: '8rem',
        duration: 0.5,
        ease: 'linear'
      });
    }
  }, [isExpanded]);

  const averageRating = (foodItem.rating / (foodItem.rating_count || 1)).toFixed(1);

  const handleRating = (newRating) => {
    updateRating(foodItem.title, newRating);
  };

  let labelsArray = [];
  try {
    if (Array.isArray(foodItem.labels)) {
      labelsArray = foodItem.labels;
    } else if (typeof foodItem.labels === "string" && foodItem.labels.trim()) {
      labelsArray = JSON.parse(foodItem.labels);
    }
  } catch (error) {
    console.error(`Error parsing labels for ${foodItem.title}:`, error);
    labelsArray = [];
  }

  const isVegetarian = labelsArray.includes("vegetarian");
  const hasGluten = labelsArray.includes("gluten");
  const highProtein = labelsArray.includes("protein");

  return (
    <div
      ref={cardRef}
      className={`relative bg-gray-700 text-white rounded-lg shadow-md p-6 cursor-pointer
       hover:bg-gray-600 transition-all duration-300 ${
        isExpanded ? "w-auto h-auto" : "w-64 h-64"
      }`}
      onClick={() => setIsExpanded(!isExpanded)}
    >
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold">{foodItem.title}</h2>
        <div className="absolute top-2 right-2 flex justify-end items-start space-x-2">
          {isVegetarian && <FaLeaf title="Vegetarian" className="text-green-400" />}
          {hasGluten && <FaBreadSlice title="Contains Gluten" className="text-yellow-500" />}
          {highProtein && <FaHandRock title="High Protein" className="text-red-400" />}
        </div>
      </div>

      <div className="flex items-center mt-2">
        <Star currentRating={averageRating} onRate={handleRating} />
        <span className="ml-2 text-sm">({foodItem.rating_count} reviews)</span>
      </div>

      {isExpanded && (
        <div className="mt-4">
          <p className="text-gray-300">{foodItem.description}</p>
          <MacroTable macros={foodItem.nutritional_info} />
          <div className="mt-2">
            <h3 className="font-semibold">Portion Size:</h3>
            <p className="text-gray-300">{foodItem.portion_size}</p>
          </div>
        </div>
      )}
    </div>
  );
}

export default FoodCard;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>