Redux-toolkit Reselect rerendering after any state change

I tried to create selector that select two variables from state and unites and returns them. But I encountered a problem, that selector causes rerendering after any state change.

import { createSelector } from 'reselect';
import { RootState } from 'store/store.ts';

const selectWallet = (state: RootState, id: string | null) => {
  if (!id) return undefined;
  return state.wallets.list[id] || undefined;
};

const selectTotal = (state: RootState, id: string | null) => {
  if (!id) return 0;
  return state.transactions.walletsTransactionsTotals[id] || 0;
};

export const reselectWalletWithTotalBalance = createSelector([selectWallet, selectTotal], (wallet, total) => {
  if (!wallet) {
    return undefined;
  }

  if (!total) {
    return wallet;
  }

  return { ...wallet, balance: wallet.balance + total };
});

export const selectWalletWithTotalBalance = (id: string | null) => {
  return (state: RootState) => reselectWalletWithTotalBalance(state, id);
};

I know that return { ...wallet, balance: wallet.balance + total }; causes rerenders, Buuut mutation selectors returning data is the point of the Reselect library (in other cases, for example when returning filtered array, no unexpected rerenders).

How to solve problem and create selector? I tryed all methods, all problems arise from creating a new object, but creating a new a object is a one of features Reselect library and I need create new object.

I tryed to reselect selectWallets and selectTotal, but nothing changed

const selectWallet = createSelector(
  [(state: RootState) => state.wallets.list, (_, id: string | null) => id],
  (walletsList, id): WalletType | undefined => {
    if (!id) return undefined;
    return walletsList[id] || undefined;
  }
);

Sweet Alert 2 v7.26.28 -> Aria hidden error in F12

(Yes, there is a new version, but right now we are not able to upgrade)

I’m using a SweetAlert2 in our Dev Express Reporting Module.

The steps are:

  1. Display Sweet Alert asking for a Report Name
  2. Do a check to the server to verify that name is not already in use
  3. If it is, show Sweet Alert message as an error
  4. On OK, then start the process again.
  5. If they hit cancel after the first run, then I see this error:

Blocked aria-hidden on a <div> element because the element that just received focus must not be hidden from assistive technology users. Avoid using aria-hidden on a focused element or its ancestor. Consider using the inert attribute instead, which will also prevent focus. For more details, see the aria-hidden section of the WAI-ARIA specification at https://w3c.github.io/aria/#aria-hidden.

It almost seems that it is an error from Sweet Alert 2, but an impact on the Dev Express Reporting Dashboard:

Error

Does anyone know a way around this or if upgrade would fix it?

All functionality seems to work, except it shows in F12 as an error.

When you hit Cancel, that the F12 Aria error does not occur.

How to override react hook form so that a value always has an id

I am working on a CMS that supports the export functionality. For most of the fields we can’t store only the value, we have to store an id with it, therefore the structure has to be like this

  task: {
    name: {
      id: <uuid>
      value: "Task 1"
    },
  }

This can be done quite easily by levering getValues and setValue functions.

Let’s say I create my custom FormInput to handle this and I use like this

<FormInput label="Task name" name='task.name.value' />

And then, on update that field, if its parent is not an object with an id then I just set it

export const FormInput = ({name}) => {
  const { register, getValues, setValue } = useForm()

  React.useEffect(() => {
    const value = getValues(name)

    if (!value) {
      const parent = name.slice(0, name.lastIndexOf(".value"))
      setValue(path, {
        id: uuidv4()
        value: // <----- here I need to get the html ref initial value based on type of the input
      })
    }
  }, [])

  return (
      <TextField fullWidth={true} {...register(name)}  />
  )
}

However the problem is that like this I override the default value. If the FormInput is of type number, and it is empty, untouched, on submit I will get NaN so I need to preserve that functionality

Playback failed: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user de

So when a user answer with the correct answer, I want to play the sound. In the contrary, I do not ant the song. This is my code:

`private async Task Notify((string message, bool success) data)
{
    if (data.success)
        await JS.InvokeVoidAsync("playCorrectAnswerSound");

    Message = data.message;
    Success = data.success;
}`

`function playCorrectAnswerSound() {
    var audio = new Audio('../sounds/CorrectAnswer.mp3');
    audio.play();
}`

This is working on Windows but when I use my Iphone there is no sound and I got the error (Playback failed: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.).

What can I do to get the sound even on IOS?

Have the sound on IOS

What is the importance of green vegetable?

Green Vegetable is most important part of our nutrition. Eat Green vegetable for good health. They can provide many nutrition and vitamin. High fiber content promotes healthy digestion, helps prevent constipation, and supports weight management.

jQuery find() cannot find an element that is the top-level element?

If I have a jQuery object, how can I search for an element that may be the top-level element?

For example, if it contains the following markup,

<tr>
    <td></td>
    <td></td>
    <td><img class="delete-transfer" src="~/images/delete.png" title="Delete Transfer" role="button" /></td>
</tr>

find() will not work if I’m looking for 'tr', because find() only appears to scan the child elements.

Is there any way to find an element that might be the top level element?

Unable to load api on server component

This is in a NextJS version 14.2.7 app.

I have setup up an api under the following path.

src/app/api/posts/route.ts

When I call it from a client component as follows, works fine.

  const loadMorePosts = async () => {
    const res = await fetch(`/api/posts?page=1&limit=20`);
    const data = await res.json();
  };

  useEffect(() => {
    if (inView) {
      loadMorePosts();
    }
  }, [inView]);

But if I call the same endpoint from a server component as follows:

import { notFound } from 'next/navigation';

const getPost = async (slug: string) => {
    const res = await fetch(`/api/posts?page=1&limit=20`); // this already breaks
    const data = await res.json();
    return data;
};

const PostDetails = async ({ slug }: { slug: string }) => {
  const post = await getPost(slug);

  // failing before even coming here.

  if (!post) {
    notFound();
  }

  return (
    <div className='container mx-auto p-4'>
        Hello
    </div>
  );
};

export default PostDetails;

I get this error:

GET /api/posts?page=1&limit=20 200 in 1069ms ✓ Compiled /post/[slug]
in 153ms (1069 modules) ⨯ Internal error: TypeError: Failed to parse
URL from /api/posts?page=1&limit=20
at node:internal/deps/undici/undici:12500:13 digest: “1300981860” Cause: TypeError: Invalid URL
at new URL (node:internal/url:804:36)
at new Request (node:internal/deps/undici/undici:4839:25)
at fetch (node:internal/deps/undici/undici:9651:25)
at fetch (node:internal/deps/undici/undici:12498:10)
at fetch (node:internal/bootstrap/web/exposed-window-or-worker:79:16)
at doOriginalFetch (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/next/dist/server/lib/patch-fetch.js:440:24)
at eval (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/next/dist/server/lib/patch-fetch.js:589:24)
at async getPost (webpack-internal:///(rsc)/./src/components/PostDetails.tsx:12:17)
at async PostDetails (webpack-internal:///(rsc)/./src/components/PostDetails.tsx:39:18) {
code: ‘ERR_INVALID_URL’, input: ‘/api/posts?page=1&limit=20’

Why? I have also tried with localhost:3000/api/posts?page=1&limit=20. Same error.

If I click a link directly from a textfield, does onblur consistently fire before the link?

I have a text input and a link used as a button set up on my website like so:

<input type="text" onblur="blurfunction()">
<a href="javascript:buttonfunction()">Button</a>

It’s important for my functionality to have blurfunction() always fire before buttonfunction(), even if the link is clicked directly without exiting the text field. From my limited testing in latest Chrome and Firefox clicking on the link directly from the text field consistently deselects the text field and fires blurfunction() before handling the link click and firing buttonfunction().

Can I expect this behaviour to be consistent across all browsers/devices? Is the order these calls happen defined in the HTML/JavaScript spec or could implementations differ between browsers?

Getting user data with Kinde auth in Remix

I am using Kinde for authentication in my remix app.

import { handleAuth, getKindeSession } from '@kinde-oss/kinde-remix-sdk'
import { LoaderFunctionArgs } from '@remix-run/node'

export async function loader({ params, request }: LoaderFunctionArgs) {
  return await handleAuth(request, params.index, {
    async onRedirectCallback() {
      const { getUserProfile } = await getKindeSession(request)
      const user = await getUserProfile()
      //TODO: Create user in Supabase
      console.log('This is called after the user is authenticated!', user)
    },
  })
}

This is the auth function. It works, I can login, log out and I have a protected page.
I am using Supabase as a database. So after authentication I want to create a profile in supabase for which I need the users details. The console.log keeps being undefined however. How can I access the user right after authentication?

how to hide the scrolled content behind the transparent sticky table head?

i am using React-Virtuoso library with material-ui table. i am stuck in a issue from yesterday,my table head is sticky and have transparent background same for table rows also. i dont want any another color.
when i scroll the table rows i can see them behind the table head. z-index cant fix the issue because of background color. please guys help me to fix this issue.
what i want is when i scroll the table rows shouldnt visible behind table head.
senior developers help needed.
codesandbox link : https://codesandbox.io/p/sandbox/epic-shtern-3jhn7q?workspaceId=b878446b-0701-41fb-b944-d231bbae84f1
here’s complete code:

import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import { TableVirtuoso } from "react-virtuoso";

const sample = [
  ["Frozen yoghurt", 159, 6.0, 24, 4.0],
  ["Ice cream sandwich", 237, 9.0, 37, 4.3],
  ["Eclair", 262, 16.0, 24, 6.0],
  ["Cupcake", 305, 3.7, 67, 4.3],
  ["Gingerbread", 356, 16.0, 49, 3.9],
];

function createData(id, dessert, calories, fat, carbs, protein) {
  return { id, dessert, calories, fat, carbs, protein };
}

const columns = [
  {
    width: 200,
    label: "Dessert",
    dataKey: "dessert",
  },
  {
    width: 120,
    label: "Caloriesu00A0(g)",
    dataKey: "calories",
    numeric: true,
  },
  {
    width: 120,
    label: "Fatu00A0(g)",
    dataKey: "fat",
    numeric: true,
  },
  {
    width: 120,
    label: "Carbsu00A0(g)",
    dataKey: "carbs",
    numeric: true,
  },
  {
    width: 120,
    label: "Proteinu00A0(g)",
    dataKey: "protein",
    numeric: true,
  },
];

const rows = Array.from({ length: 200 }, (_, index) => {
  const randomSelection = sample[Math.floor(Math.random() * sample.length)];
  return createData(index, ...randomSelection);
});

const VirtuosoTableComponents = {
  Scroller: React.forwardRef((props, ref) => (
    <TableContainer {...props} ref={ref} />
  )),
  Table: (props) => (
    <Table
      {...props}
      sx={{
        borderCollapse: "separate",
        borderSpacing: "0px 8px",
      }}
    />
  ),
  TableHead: React.forwardRef((props, ref) => (
    <TableHead
      {...props}
      ref={ref}
      style={{
        background: "rgba(255, 255, 255, 0.1)",
        position: "sticky",
        zIndex: 2,
        top: "8px",
      }}
    />
  )),
  TableRow: React.forwardRef((props, ref) => (
    <TableRow
      {...props}
      ref={ref}
      sx={{
        background: "rgba(255, 255, 255, 0.1)",
      }}
    />
  )),
  TableBody: React.forwardRef((props, ref) => (
    <TableBody {...props} ref={ref} />
  )),
};

function fixedHeaderContent() {
  return (
    <TableRow>
      {columns.map((column) => (
        <TableCell
          key={column.dataKey}
          variant="head"
          align={column.numeric || false ? "right" : "left"}
          sx={{
            borderTop: "1px solid rgba( 255, 255, 255, 0.18 )",
            borderBottom: "1px solid rgba( 255, 255, 255, 0.18 )",
            "&:first-of-type": {
              borderLeft: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopLeftRadius: "10px",
              borderBottomLeftRadius: "10px",
            },
            "&:last-of-type": {
              borderRight: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopRightRadius: "10px",
              borderBottomRightRadius: "10px",
            },
          }}
        >
          {column.label}
        </TableCell>
      ))}
    </TableRow>
  );
}

function rowContent(_index, row) {
  return (
    <React.Fragment>
      {columns.map((column) => (
        <TableCell
          key={column.dataKey}
          align={column.numeric || false ? "right" : "left"}
          style={{
            borderTop: "1px solid rgba( 255, 255, 255, 0.18 )",
            borderBottom: "1px solid rgba( 255, 255, 255, 0.18 )",
            "&:first-of-type": {
              borderLeft: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopLeftRadius: "10px",
              borderBottomLeftRadius: "10px",
            },
            "&:last-of-type": {
              borderRight: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopRightRadius: "10px",
              borderBottomRightRadius: "10px",
            },
          }}
        >
          {row[column.dataKey]}
        </TableCell>
      ))}
    </React.Fragment>
  );
}

export default function ReactVirtualizedTable() {
  return (
    <div
      style={{
        height: 400,
        width: "100%",
        background: "rgba(255, 255, 255, 0.1)",
      }}
    >
      <TableVirtuoso
        data={rows}
        components={VirtuosoTableComponents}
        fixedHeaderContent={fixedHeaderContent}
        itemContent={rowContent}
      />
    </div>
  );
}

i dont want to see table row scrolled behind the table head.

How to call a js function that is fetched?

I have a react app where I try to fetch some functions from a js file:

useEffect(() => {
  const todayDate = new Date();

  fetch("https://raw.githubusercontent.com/courseraap/capstone/main/api.js")
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.text();
    })
    .then((textResponse) => {
      console.log("textResponse :>> ", textResponse);

      const scriptFunction = new Function(textResponse);
      scriptFunction();

      window.fetchAPI(todayDate); // error, it is not a function. window.fetchAPI is undefined

    });

}, []);

I’ve read that if I call the response this way it will add those function objects to the window object, which is not happening for me for some reasons. What am I missing here?

The url is valid, so it can be checked the function is there.

Making calculations in a HTML table

I have a created a HTML table which is editable.
The table contains some cells are predefined with the numbers 1-5, than there is section where the user can enter data and in the last column there should be the result of the data of the previous cells. Now I want the add a formula like you have for instances with Excel. How I can make calculations in the HTML table with Javascript or any other method?

Details table

enter image description here

Column 1: packages is predefined
Column 2: here user can add weight in kg
Column 3: user adds here the length
Column 4: user adds here the width
Column 5: user adds here height
Column 6: user adds split (%)
Column 7: Volume weight = result formule is:length x width x height x 200

HTML table

.package_details {
  overflow: auto;
  width: 100%;
}

.package_details table {
  border: 1px solid #000000;
  height: 100%;
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
  border-spacing: 1px;
  text-align: center;
}

.package_details caption {
  caption-side: top;
  text-align: left;
}

.package_details th {
  border: 1px solid #000000;
  background-color: #5A7C95;
  color: #ffffff;
  padding: 5px;
}

.package_details td {
  border: 1px solid #000000;
  background-color: #ffffff;
  color: #000000;
  padding: 5px;
}
</p>
<div class="package_details" tabindex="0" role="region">
  <table>
    <caption>
      <p><strong>Volume weight = L X W X H * 200</strong></p>
    </caption>
    <thead>
      <tr>
        <th>Packages</th>
        <th>Weight (kg)</th>
        <th>
          <p>Length (cm)</p>
        </th>
        <th>Width (cm)</th>
        <th>Height (cm)</th>
        <th>Split (%)</th>
        <th>*Volume weight</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>2</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>3</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>4</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>5</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
    </tbody>
  </table>
  <div style="margin-top: 8px;"> </div>
</div>

What I tried
I did some research and many posts mention adding javascript to make calculations. I tried some but no success. Further I tried to add a formula in the last column to make calculations. Sadly not results.

What are some lesser-known JavaScript tips or keyboard shortcuts that have significantly improved your productivity as a developer? [closed]

I’m working on improving my JavaScript skills and trying to boost my productivity while coding. I know there are many helpful tips and keyboard shortcuts that can make coding faster and more efficient, but I feel like I’m missing out on some of the more advanced tricks. I’d love to hear about any tips, shortcuts, or practices that others have found really useful in their day-to-day development.

I’ve tried using some basic keyboard shortcuts like Ctrl + / to comment code and Alt + Shift + F for auto-formatting, but I feel like there’s more I could be leveraging.

‘Multipart: Boundary not found’ with React Fetch POST request, but works with Postman

I’m trying to send an image and two text fields to the express server, but it gives the error “Multipart: Boundary not found”.

    const handleFileUpload = async () => {
    if (!selectedFile) {
      Alert.alert('Ошибка', 'Выберите файл для загрузки');
      return;
    }
  
    const formData = new FormData();
    formData.append('image', {
      uri: selectedFile.uri,
      type: selectedFile.type,
      name: selectedFile.fileName || 'image.png',
    });
    formData.append('title', newImageTitleFile);
    formData.append('description', newImageDescriptionFile);
  
    try {
      const response = await fetch('http://localhost:5000/api/images/upload', {
        method: 'POST',
        body: formData,
      });
  
      if (!response.ok) {
        throw new Error('Ошибка загрузки файла');
      }
  
      const data = await response.json();
      console.log('Загружено:', data);
    } catch (error) {
      console.error('Ошибка:', error);
    }
  };

I tried to remove the header ‘Content-Type’: ‘multipart/form-data’, nothing changes.