Firebase messaging in React Native always returns Denied

I’m trying to implement push notifications with React Native and in IOS even though I touch allow when the prompt for push notifications show up, it still returns denied. Below is my code. Any help is appreciated on this.

import { getApp } from '@react-native-firebase/app';
import {
  getMessaging,
  requestPermission,
  getToken,
  onMessage,
  AuthorizationStatus,
  registerDeviceForRemoteMessages,
} from '@react-native-firebase/messaging';

export default function SetPushNotification() {
  useEffect(() => {
    (async () => {
      
      const authStatus = await requestPermission(getMessaging(getApp()));
     
      if (authStatus === AuthorizationStatus.AUTHORIZED ||
          authStatus === AuthorizationStatus.PROVISIONAL) {
            
      await registerDeviceForRemoteMessages(getMessaging(getApp()));
        const token = await getToken(getMessaging(getApp()));
        console.log('FUCK', authStatus)
        console.log('FCM Token (modular):', token);
      }
    })();

    const unsubscribe = onMessage(getMessaging(getApp()), async remoteMsg => {
      Alert.alert('Modular FCM Message', JSON.stringify(remoteMsg));
    });

    return unsubscribe;
  }, []);

  return null;
}

I tried everything. I expect that the status of the authorization code would be 3 or authorized when I tap allow.

Checking product availability and quantity validity | AssertionError: The server response does not contain the ‘products’ field or is not valid JSON

[Javascript]

Response code 200 or 201 | AssertionError: expected 500 to be one of [ 200, 201 ]
Checking product availability and quantity validity | TypeError: Cannot read properties of undefined (reading ‘hasOwnProperty’)

{
“timestamp”: “2025-03-29T01:59:18.976+00:00”,
“status”: 500,
“error”: “Internal Server Error”,
“path”: “/api/v1/shopping-cart”
}

Pre-request

const main = async () => {
    const api = new API(pm);
    const rnd = new RandomUtils();

try {
    pm.collectionVariables.set("userName", rnd.getWord(10));
    product1 = rnd.getProductForWarehouse();
    product2 = rnd.getProductForWarehouse();
    await api.addProductToWarehouse(product1);        
    await api.addProductToWarehouse(product2);
    
    productList = {
        [product1.productId]: Math.floor(Math.random() * 1000), // Случайное число до 1000
        [product2.productId]: Math.floor(Math.random() * 1000)  // Случайное число до 1000
    };
    
    pm.collectionVariables.set("productList", productList); // Сохраняем productList, если нужно
} catch (err) {
    console.error("Ошибка при подготовке тестовых данных.", err);
}

    pm.request.body.update({
        mode: 'raw',
        raw: JSON.stringify(productList),
        options: { raw: { language: 'json' } }
    });
};

const interval = setInterval(() => {}, 1000);

setTimeout(async () => 
    {
        try {
            await main();
        } catch (e) {
            console.error(e);
        } finally {
            clearInterval(interval);
        }
    },  
    100 
);

Post-response

pm.test("Код ответа 200 или 201", function () {
    pm.expect(pm.response.code).to.be.oneOf([200, 201]);
});

const productList = pm.collectionVariables.get("productList"); 
const products = pm.response.json().products;

pm.test("Проверка наличия продуктов и валидности количества", function () {
    let allKeysPresent = true;
    let valuesValid = true;
    for (key in productList) {
        if (!products.hasOwnProperty(key)) {
            allKeysPresent = false;
            break;
        }
        if (products[key] < productList[key]) {
            valuesValid = false;
        }
    }

    pm.expect(allKeysPresent).to.be.true;
    pm.expect(valuesValid).to.be.true;
});

Why is this code not working as indtended?

So I decided to make a small website thing called “The List of Truth”, where the user inputs one of the options and the website spits out “The Truth” about said option. However, it’s constantly stuck on outputting ONLY “The Truth” about carrot sticks.

Can someone help me debug this code? I don’t know much javascript, so if anyone could, that would be really helpful.

Oh, and here’s the linkie to the site.

I’ve already tried using tutorials and other posts on stackoverflow, but none of them seem to work.

How to get average on timestmapDiff in prisma queries

I am trying to get convert a raw sql query to prisma, but i can’t find a way to average on a “virtual” column which is the difference between 2 date columns

IFNULL(AVG(CASE WHEN end_time IS NOT NULL THEN TIMESTAMPDIFF(SECOND, start_time, end_time) ELSE 0 END),
                      0) / 60                                                                                  AS average_duration,

there doesn’t seem to be any documentation on this case (even thought it’s trivial)

Authentication with the MERN stack not working after some time

I’m very new to using the MERN stack so forgive me if this is a simple fix. I’m created an application using the MERN stack and when I go to log in, I can’t log in using the old accounts stored in the database, only new ones. I can constantly log in and out of the new ones, but the old ones can’t log in even once. I’m using jsonwebtoken (JWT) and bcrypt (bcrypt.compare() to be exact) for logging in.

I printed the hashed password into the console, and it matches the password in the database. If I try to sign up using the same email, it throws an error saying that the email already exists in the database. So it’s clear that it can recognize the user in the database, but it’s struggling to log in with old account.

Login Function:

import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";

export const login = async (request, response) => {
  try {
    const { email, password } = request.body;
    if (!email || !password) {
      return response.status(400).send("Email and password are required");
    }

    const user = await User.findOne({ email });
    if (!user) {
      return response.status(400).send("Email not registered");
    }

    const auth = await bcrypt.compare(password, user.password);

    if (!auth) {
      return response.status(400).send("Incorrect password");
    }

    response.cookie("jwt", createToken(email, user.id), {
      maxAge,
      secure: true,
      sameSite: "None",
    });

    return response.status(200).json({
      user: {
        id: user.id,
        email: user.email,
        profileSetup: user.profileSetup,
        firstName: user.firstName,
        lastName: user.lastName,
        image: user.image,
        color: user.color,
      },
    });
  } catch (error) {
    console.error(error);
    return response.status(500).send("Internal server error");
  }
};

When I try running my code, I get this error:

response: {data: ‘Incorrect password’, status: 400, statusText: ‘Bad Request’, headers: AxiosHeaders, config: {…}, …}

The error is a lot longer than that, but that should be information to know that something isn’t right. I know it’s the right password, I cross verified it with printing it out, and it’s still throwing errors. I was expecting it to log in, but it just throws that error every time I press the login button

Guidelines or best practices for writing predictable, maintainable JavaScript code?

I come from a background in statically typed languages like C, C++, and Java, and I’m currently working on a project that uses JavaScript as the main language. I’ve noticed JavaScript has many unique features (like hoisting, implicit globals, different function invocation behaviors, prototype-based inheritance, and so on) that sometimes lead to confusing or unexpected behavior.

I’ve read up on concepts like “use strict,” avoiding implicit globals, and other style recommendations, but I still want to ensure my code remains predictable and straightforward. My question is:

  • What concrete guidelines or best practices can help me minimize surprises in JavaScript code?

  • Which common pitfalls and language “gotchas” should I actively avoid, and how?

  • Are there specific patterns or coding styles (e.g., recommended naming conventions, file structures, or design patterns) that help ensure clarity and maintainability?

I’m looking for strategies that keep the code base easy to reason about, especially for someone coming from more strictly typed languages. Although I heard about TypeScript as an alternative solution, I wish to do it in JavaScript way.

My effort:

  • Try 'use strict'; to avoid accidental globals – but strict mode also affects many other behaviors.
  • Keep function small and avoid ‘magical’ features of this language
  • I was recommended to read style guides like Airbnb‘s and Google‘s.
  • Always try to conform KISS principle

However, I would appreciate more direct, practical advice or references (like well-known “dos and don’ts” lists or style guides) that help enforce predictable behavior in day-to-day coding.

How to detect a Javascript click button event in a WKWebView?

import UIKit
import WebKit
import AppTrackingTransparency

class ViewController: UIViewController {
    
    let webView: WKWebView = {
        let prefs = WKWebpagePreferences()
        prefs.allowsContentJavaScript = true
        let configuration = WKWebViewConfiguration()
        configuration.defaultWebpagePreferences = prefs
        
        let webView = WKWebView(frame: .zero,
                                configuration:configuration)
        return webView
    }()
    

    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        view.bounds = view.safeAreaLayoutGuide.layoutFrame
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestTrackingPermission()
        view.addSubview(webView)
   
        guard let url = URL(string: "https://enter.markets")else{
            return
        }

        webView.isOpaque = false
        webView.load(URLRequest(url: url))
        
        
    }
    
    func requestTrackingPermission() {
      
               ATTrackingManager.requestTrackingAuthorization { status in
                   switch status {
                       case .notDetermined:
                            print("Tracking authorization not determined")
                       case .restricted:
                            print("Tracking authorization restricted")
                       case .denied:
                            print("Tracking authorization denied")
                       case .authorized:
                            print("Tracking authorization granted")
                       @unknown default:
                            print("Unknown tracking authorization status")
                    }
               }
  
            }
   
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        webView.frame = view.bounds
    }
}

I am running a WKWebView with this code.
I am opening a webpage.
For example, when I click on the id playtest button on the webpage, it needs to give an alert via Swift code or run another function.

I tried some sample code but I couldn’t figure it out.

R Shiny Custom Sorting for DataTables with DOM

I am trying to build a shiny app with datatables. The issue is that for one of my datatables I need to sort the columns in a non-standard way something similar to

https://northcoder.com/post/custom-sorting-and-column-types-in/#the-sorting-functions

and I can implement this sorting via Header clicking controls

In my real example I am sorting a column with number ids but mixed with strings in the same column. Regardless in the below example is if you wanted to sort a table by column based on defined “Levels” of high, medium, and low. I have tried many different ways some that use data directly and table.clear() in the callback = DT function.

so that in descending it would be High, then medium then low. and ascending Low, medium then high

if anyone has a solution to this I would be very grateful

library(shiny)
library(DT)

ui <- fluidPage(
  tags$head(
    tags$script(HTML("
  function whenDataTableAvailable(callback) {
    if (window.jQuery && jQuery.fn && jQuery.fn.dataTable) {
      callback();
    } else {
      setTimeout(function() { whenDataTableAvailable(callback); }, 50);
    }
  }

  whenDataTableAvailable(function() {
    jQuery.fn.dataTable.ext.type.order['custom-level-pre'] = function(d) {
      switch(d) {
        case 'Low': return 1;
        case 'Medium': return 2;
        case 'High': return 3;
        default: return 0;
      }
    };
  });
"))
    
  ),
  DTOutput("mytable")
)

server <- function(input, output, session) {
  output$mytable <- renderDT({
    datatable(
      data.frame(
        ID = 1:5,
        Priority = c("Medium", "Low", "High", "Medium", "Low")
      ),
      options = list(
        columnDefs = list(
          list(
            targets = 1,
            type = 'custom-level'
          )
        )
      )
    )
  }, server = FALSE) 
  
  
}

shinyApp(ui, server)

GoogleChart fetch data from server when zooming or paning inside the LineChart

I try to implement a Google Chart displaying sensor value in a time line. I want to have the min, max and average value in the graph (min and max is a filled interval). But I want also the chart to be more interactive by implementing a zoom inside the data : when the user zoom in the chart, data are fetched again from the server with updated values based on the selected time range during the zoom.

For example, when the user is zoomed out in a time window for a full month, the data are aggregated by day. But if the user zoom to a day, a server call should retreive data aggregated by hours. If he zoom to an hour, data are aggregated by seconds.

Unfortunately, I’m not able to make it works, because I do not find any trigger when the user zoom. I did addListener on rangechange but this event is never called.

Here is the Fiddle :
https://jsfiddle.net/93na1tcq/

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Line Chart Example</title>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">
    google.charts.load("current", {
      packages: ["corechart"],
      callback: initGraph,
    })
    
    function initGraph() {
      data = new google.visualization.DataTable()
      data.addColumn("datetime", "DateTime")
      data.addColumn("number", "values") // average
      data.addColumn({ id: "i0", type: "number", role: "interval" }) // min
      data.addColumn({ id: "i1", type: "number", role: "interval" }) // max
      jsonData = fetchData()
      data.addRows(jsonData)
      options = {
        title: "Min, Max, and Average Values Over Time",
        intervals: { style: "area" },
        hAxis: {
          title: "Date",
          format: "MMM dd, yyyy",
        },
        vAxis: {
          title: "Values",
        },
        legend: { position: "bottom" },
        explorer: {
          actions: ["dragToZoom", "rightClickToReset"],
          axis: "horizontal",
          keepInBounds: true,
          maxZoomIn: 0.1,
        },
      }
    
      chart = new google.visualization.LineChart(
        document.getElementById("chart_div"),
      )
      google.visualization.events.addListener(chart, "ready", addZoomListener)
      chart.draw(data, options)
    }
    
    function fetchData(
      startDate = "2025-03-01T00:00:00Z",
      endDate = "2025-03-05T00:00:00Z",
    ) {
      /**
                const url = `data.php?fmt=json&agregate=86400&startdate=${startDate}&enddate=${endDate}`;
    
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        const formattedData = [['Date', 'Min', 'Average', 'Max']];
                        data.forEach(item => {
                            formattedData.push([new Date(item[0]), item[1], item[2], item[3]]);
                        });
                        drawChart(formattedData);
                    })
                    .catch(error => console.error('Error fetching data:', error));
    **/
    
      formattedData = [] // Date, avg, min, max
      formattedData.push([new Date("2025-03-23T23:00:00.000Z"), 10.0, 5, 20.0])
      formattedData.push([new Date("2025-03-24T23:00:00.000Z"), 15.0, 10.0, 30.0])
      formattedData.push([new Date("2025-03-25T23:00:00.000Z"), 35.0, 20.0, 45.0])
      formattedData.push([new Date("2025-03-26T23:00:00.000Z"), 35.0, 30.0, 50.0])
      formattedData.push([new Date("2025-03-27T23:00:00.000Z"), 55.0, 50.0, 60.0])
      return formattedData
    }
    
    function addZoomListener() {
      google.visualization.events.addListener(chart, "rangechange", function () {
        alert("rangechange")
        const viewWindow = chart.getOption("hAxis.viewWindow")
        const startDate = new Date(viewWindow.min).toISOString()
        const endDate = new Date(viewWindow.max).toISOString()
        fetchData(startDate, endDate)
      })
    
      google.visualization.events.addListener(chart, "select", function () {
        alert("select")
      })
    }
        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;"></div>
    </body>
    </html>

You can zoom on the graph by drag&drop in the chart, right click to zoom out. I was not able to implement slide or panning to.
The JS function fetchData() simulate the call to the server.

How to trigger an event when the user zoom on the chart ?

Why docker watch not listen to local changes

I’m trying to use docker develop watch with docker bake but when i make changes to let’s say back/src/views it does not get reflected to the running container

folder strucure

front
back
deploy

deploy/front.dockerfile

FROM node:bullseye-slim
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /app
COPY front/package.json front/pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/pnpm/store 
    pnpm install --frozen-lockfile
COPY front/ ./
EXPOSE 8080
CMD [ "pnpm", "dev" ]

deploy/back.dockerfile

FROM node:bullseye-slim
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV NODE_ENV=development
RUN corepack enable
WORKDIR /app
COPY back/package.json back/pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/pnpm/store 
    pnpm install --frozen-lockfile
COPY back/ ./
EXPOSE 3000
CMD [ "pnpm", "dev" ]

deploy/nginx.dockerfile

FROM nginx:alpine
COPY ./deploy/nginx.conf /etc/nginx/nginx.conf
COPY ./deploy/virtualhost.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
STOPSIGNAL SIGTERM
CMD ["nginx", "-g", "daemon off;"]

compose.yaml

services:
  front:
    image: front
    build:
      context: .
      dockerfile: ./deploy/front.dockerfile
    develop:
      watch:
        - path: front/package.json
          action: rebuild
        - path: front/pnpm-lock.yaml
          action: rebuild
        - path: front/
          target: /app
          action: sync

  nginx:
    image: nginx
    ports:
      - '3000:80'
      - '443:443'
    volumes:
      - ./front/static:/usr/share/nginx/static:ro
    depends_on:
      - front
      - back

  back:
    image: back
    build:
      context: .
      dockerfile: ./deploy/back.dockerfile
    develop:
      watch:
        - path: back/package.json
          action: rebuild
        - path: back/pnpm-lock.yaml
          action: rebuild
        - path: back/
          target: /app
          action: sync

bake.hcl

group "default" {
  targets = ["front", "nginx", "back"]
}

target "front" {
  dockerfile = "./deploy/front.dockerfile"
  tags = ["front"]
}

target "nginx" {
    dockerfile = "./deploy/nginx.dockerfile"
    tags = ["nginx"]
}

target "back" {
  dockerfile = "./deploy/back.dockerfile"
  tags = ["back"]
}

i tried to add volumes and it worked but i want to use the watch command

Snap drag to center on motion react

I’m relatively new to motion, and I’m making this carousel that you scroll on drag. However the only issue is that the elements don’t snap at the center when I drag.

Here’s the code

import { useRef } from "react";
import { motion, useMotionValue, useTransform } from "framer-motion";

const pages = [1, 2, 3, 4, 5];

export default function DragPage() {
  const containerRef = useRef(null);
  const x = useMotionValue(0);

  return (
    <div className="w-screen h-screen bg-pink-950 flex justify-center items-center">
      <motion.div
        ref={containerRef}
        className="border-4 p-4 overflow-x-hidden flex cursor-grab w-42 snap-center"
      >
        {pages.map((_, index) => {
          const itemOffset = -index * 150;
          const offset = useTransform(
            x,
            [itemOffset - 150, itemOffset, itemOffset + 150],
            [-1, 0, 1]
          );
          const itemOpacity = useTransform(offset, [-1, 0, 1], [0.4, 1, 0.4]);
          const itemScale = useTransform(offset, [-1, 0, 1], [0.5, 1, 0.5]);
          const itemX = useTransform(offset, [-1, 0, 1], [20, 0, -20]);

          return (
            <motion.div
              key={index}
              drag="x"
              dragConstraints={{ left: -500, right: 0 }}
              className="bg-white rounded-2xl w-32 h-32 flex-shrink-0"
              style={{
                opacity: itemOpacity,
                scale: itemScale,
                x: itemX,
                x,
              }}
            />
          );
        })}
      </motion.div>
    </div>
  );
}

I’ve tried applying the scroll-snap on tailwind class but I realize that only works for scroll which isn’t what I implemented here.

Whenver i use useRecoilState why does my component not load

React + Recoil: useRecoilValue() Causes Component to Not Load, but useRecoilState() Works
I am working on a React project where App.jsx is my main rendered component. Within it, I have wrapped my component inside to ensure proper state management using Recoil.

In Calculator.jsx, I am using Recoil to manage a piece of global state called Stake, which is defined as an atom in IPL.js. My atom definition looks like this:

IPL.js-

import { atom } from "recoil";

const Stake = atom(
    {
        key:"Stake",
        default:{
            valueA:1.0,
            valueB:1.0
        }
   }
);



const Amount = atom({
    key:"Amount",
    default:{
        valueA:0.0,
        valueB:0.0
    }
});

const Profit = atom({
    key:"Profit",
    default:{
        valueA:0.0,
        valueB:0.0,
        Total:0.0
    }
}); 

export  { Stake , Amount , Profit };

calculator.jsx –

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { colors } from '@mui/material';
import Grid from "@mui/material/Grid2"
import * as Recoil from 'recoil';
import { Stake,Amount,Profit } from '../store/atoms/IPL'



export default function Calculator(){
  const [stakeValue,setStakeValue] = Recoil.useRecoilState(Stake);

  const [stakeA,setStakeA] = React.useState(1.0);
  const [stakeB,setStakeB] = React.useState(1.0);

  const [amount,setAmount] = Recoil.useRecoilState(Amount);
  const [amountA,setAmountA] = React.useState(0.0);
  const [amountB,setAmountB] = React.useState(0.0);

  // const [profit,setProfit] = useRecoilState(Profit);
  const [maxProfit,setMaxProfit] = React.useState(0.0);



  
  return(<div>
  <h1>Pseudo-Aribtrage calculator</h1>
  <Box
      component="form"
      sx={{ '& > :not(style)': { m: 1 ,width:"75ch"} }}
      noValidate
      autoComplete="off"
    >
  <Grid container spacing={1}>
        <Grid size={2}>
        {/* <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setStake((prev) => ({ ...prev, valueA: val }));}} type="float" sx={{ '& > :not(style)': {  bgcolor:'#213547' } }} label={"Stake A"} variant="outlined" /> */}
        <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setStakeA(val)}} sx={{ '& > :not(style)': {  bgcolor:'#213547' } }} label={"Stake A"} variant="outlined" />
        </Grid>
        <Grid size={5}>
        {/* <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setAmount((prev) => ({ ...prev, valueA: val }));}} type="float" sx={{ '& > :not(style)': {  bgcolor:'#213547',margin:"2px"  } }} label="Enter amount Team A" variant="outlined" /> */}
        <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setAmountA(val)}}  sx={{ '& > :not(style)': {  bgcolor:'#213547',margin:"2px"  } }} label="Enter amount Team A" variant="outlined" />
        </Grid>
        <Grid size={2.5}>
        <TextField id="outlined-basic" onChange={{}} sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label="Min Loss" variant="outlined" />
        </Grid>
        <Grid size={2.5}>
        <TextField id="outlined-basic" onChange={{}} sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label="Max Loss" variant="outlined" />
        </Grid>
        
        <Grid size={2}>
        {/* <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setStake((prev) => ({ ...prev, valueB: val }));}}  type="float" sx={{ '& > :not(style)': {  bgcolor:'#213547' } }} label="Stake B" variant="outlined" /> */}
        <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setStakeB(val)}}  type="float" sx={{ '& > :not(style)': {  bgcolor:'#213547' } }} label="Stake B" variant="outlined" />
        </Grid>
        <Grid size={5}>
        {/* <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setAmount((prev) => ({ ...prev, valueB: val }));}} type="number" sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label="Enter amount Team B" variant="outlined" /> */}
        <TextField id="outlined-basic" onChange={(e) => {const val = parseFloat(e.target.value) || 0;setAmountB(val)}}  sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label="Enter amount Team B" variant="outlined" />
        </Grid>
        <Grid size={2.5}>
        <TextField id="outlined-basic" onChange={{}} sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label="Min Profit" variant="outlined" />
        </Grid>
        <Grid size={2.5}>
        <TextField id="outlined-basic" onChange={{}} sx={{ '& > :not(style)': {  bgcolor:'#213547'  } }} label={(amountA*stakeA)+(amountB*stakeB)} variant="outlined" />
        </Grid>
      </Grid>
    </Box>
    </div>)
  
}

App.jsx-

import { useState } from 'react'
// import reactLogo from './assets/react.svg'
// import viteLogo from '/vite.svg'
import './App.css'
import { RecoilRoot } from 'recoil'
import Calculator from './components/calculator'
import {BrowserRouter as Router,Routes,Route} from 'react-router'
function App() {
  // const [count,setCount] = useState(0)


  return (
    
    <RecoilRoot>
    <Router>
      <Routes>
        <Route  path='/' element={<Calculator />} />
      </Routes>
    </Router>
    </RecoilRoot>
    
  )
}

export default App;

Issue:
When I use const stakeState = useRecoilState(Stake);, the Calculator component renders correctly.

However, when I use const stakeValue = useRecoilValue(Stake);, the Calculator component does not load at all.

There are no key conflicts, and I have ensured that is correctly wrapping .

I am using the latest versions of React (18.x) and Recoil (0.7.x).

What I Have Tried:
Wrapping inside to ensure the atom is accessible.

Ensuring there are no conflicting keys in atom definitions.

Checking for any syntax errors or import issues.

Trying useRecoilState(Stake), which works fine.

Question:
Why does useRecoilState(Stake) cause my component to not load, and how do i fix it

Would appreciate any insights!

Creating npm packages for both CJS and ESM using the exports property

The library mode documentation for Vite has an example of a package.json that uses require for UMD modules and import for ESM and this is the example:

{
  "name": "my-lib",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/my-lib.umd.cjs",
  "module": "./dist/my-lib.js",
  "exports": {
    ".": {
      "import": "./dist/my-lib.js",
      "require": "./dist/my-lib.umd.cjs"
    }
  }
}

Are the import and require keywords in this case used as “conditional keywords” that toggle the module file resolution?

So if a developer is using ESM syntax and they do something like:

import { Foo } from { my-lib }

then the import will resolved from "./dist/my-lib.js" and if they do:

const myLib = require('my-lib')

then the import will be resolved from ./dist/my-lib.umd.cjs?

Also if we are making use of the exports property like this do we still need main and module?

It seems like these are overlapping?

Which Text Editor library supports React 19? [closed]

I need to include a Rich Text Editor in my react 19 application. Most of the text editor libraries require react 18 and below for them to work. Is there any library which supports React 19. PS – Im cannot downgrade my react application version.

I tried downloading text editor libraries in react 19 application but encountered peer dependency errors.

How to solve the issue to display the stereoscopic view in the Html

I am Derby. I am new in this community. I would need the help to solve the issue for modifying the code for the display of the stereoscopic view as the result of the demonstration on the website “3d-stereo-html5” (https://github.com/moul/3d-stereo-html5?tab=readme-ov-file). The source code is from the project entitled “3d-stereo-html5” (https://github.com/moul/3d-stereo-html5?tab=readme-ov-file). I cannot perform the effects like the half color anaglyphs and other selections under the section of the 3D Renderers and not 3d effect both as the demonstration on the website “3d-stereo-html5″(https://github.com/moul/3d-stereo-html5?tab=readme-ov-file). The image can only show the original stereoscopic photo on the web page but cannot perform the stereoscopic effect. Attached is the source code. I hope to post the result of the image to explain clearly, but I am not allowed to put the image here. I wish the source code and the link from one old project would help you solve the problem and provide the solutions based on your specialty. Thank you.

<!DOCTYPE html>
<html>

<body>
    <select onChange="javascript:img.src=this.value">
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/statue2-3D-side-by-side-960.jpg">statue2-3D-side-by-side-960.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/5310631602_dc8361d16e.jpg">5310631602_dc8361d16e.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/masters3dsidebyside1.jpg">masters3dsidebyside1.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/side-by-Side-LCI.jpg">side-by-Side-LCI.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/G-Force-trailer-3D.jpg">G-Force-trailer-3D.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/side-by-side-3d.jpg">side-by-side-3d.jpg</option>
      <option value="/Private Documents/Web/Stereoscopic Art/3d-stereo-html5-master/images/5305857371_a7b21074a2.jpg">5305857371_a7b21074a2.jpg</option>
    </select>

    <select onChange="javascript:algorythm=this.value;handleImg(img);">
      <option value="default" selected>Default</option>
      <optgroup label="3d renderers">
        <option value="true-anaglyphs">True Anaglyphs</option>
        <option value="optimized-anaglyphs">Optimized Anaglyphs</option>
        <option value="gray-anaglyphs">Gray Anaglyphs</option>
        <option value="color-anaglyphs">Color Anaglyphs</option>
        <option value="half-color-anaglyphs">Half Color Anaglyphs</option>
      </optgroup>
      <optgroup label="not 3d effects">
        <option value="grayscale">Grayscale</option>
        <option value="brightness">Brightness</option>
        <option value="threshold">Threshold</option>
      </optgroup>
    </select>

<script>
var canvas = document.createElement("canvas");
var canvas2 = document.createElement("canvas");
var algorythm = "default";
var img = new Image;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");


      img.onload = function() {
        handleImg(img);
      };

      function handleImg(img) {
        halfWidth = img.width / 2;
        canvas.width = img.width;
        //canvas.width = halfWidth;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        var pixels = imageData.data;
        console.info("canvas.width", canvas.width);
        console.info("canvas.height", canvas.height);
        console.info("pixels.length", pixels.length);
        for (var i = 0, il = pixels.length; i < il; i+= 4) {
          //var color = Math.random() * 255;
          if ((i / 4) % img.width < img.width / 2) {
            var r1 = pixels[i + 0],
              r2 = pixels[i + 0 + img.width * 2],
              g1 = pixels[i + 1],
              g2 = pixels[i + 1 + img.width * 2],
              b1 = pixels[i + 2],
              b2 = pixels[i + 2 + img.width * 2],
              ra = 0,
              ga = 0,
              ba = 0;

            switch (algorythm) {
            case "true-anaglyphs":
              ra = 0.299 * r1 + 0.587 * g1 + 0.114 * b1;
              ba = 0.299 * r2 + 0.587 * g2 + 0.114 * b2;
              break;
            case "optimized-anaglyphs":
              ra = 0.7 * g1 + 0.3 * b1;
              ga = g2;
              ba = b2;
              break;
            case "gray-anaglyphs":
              ra = 0.299 * r1 + 0.587 * g1 + 0.114 * b1;
              ga = ba = 0.299 * r2 + 0.587 * g2 + 0.114 * b2;
              break;
            case "color-anaglyphs":
              ra = r1;
              ga = r2;
              ba = b2;
              break;
            case "half-color-anaglyphs":
              ra = 0.299 * r1 + 0.587 * g1 + 0.114 * b1;
              ga = r2;
              ba = b2;
              break;
            case "grayscale":
              var v = 0.299 * r1 + 0.587 * g1 + 0.114 * b1;
              ra = ga = ba = v;
              break;
            case "brightness":
              var adjustment = 100;
              ra = r1 + adjustment;
              ga = g1 + adjustment;
              ba = b1 + adjustment;
              break;
            case "threshold":
              var v = (r1 + 0.2126 * r1 + 0.7152 * g1 + 0.0722 * b1) ? 255 : 0;
              ra = ga = ba = v;
            break;
            case "default":
              ra = r1;
              ga = g1;
              ba = b1;
              break;
            default:
              break;
            }
          } else {
            ra = 255;
            ga = 255;
            ba = 255;
          }
          pixels[i + 0] = ra;
          pixels[i + 1] = ga;
          pixels[i + 2] = ba;
        }
        
        ctx.putImageData(imageData, 0, 0);
        
        canvas2.width = img.width;
        canvas2.height = img.height;
        canvas.style.display = 'block';
        var ctx2 = canvas2.getContext("2d");
        ctx2.drawImage(img, 0, 0);

        document.body.appendChild(canvas);
        document.body.appendChild(canvas2);

      };
img.src="5305857371_a7b21074a2.jpg";
</script>

</body>

</html>