How to get values of the first element of fetch reponse

I try to get values of the first element of my fetch request.

Here you can see my code -> the result of the fetch-request is assigned to “data” variable.

const ListRezept = (props) => {
   const url_id = props.params.id;
   const [data, setData] = useState(null);
   const [isPending, setIsPending] = useState(true);
   const [error, setError] = useState(null);
  
   useEffect(() => {
    const abortCont = new AbortController();

    setTimeout(() => {
    fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id)
       .then(res => {
          if (!res.ok) { // error coming back from server
            console.log("error");
            throw Error('Could not fetch the data for that resource!');
          } 
          return res.json();
       })
       .then(data => {
        setIsPending(false);
        setData(data.value);
        setError(null);
       })
       .catch(err => {
        if (err.name === 'AbortError') {
          console.log('fetch aborted')
        } else {
          // auto catches network / connection error
          setIsPending(false);
          setError(err.message);
        }
       });
 }, []);

     // abort the fetch
     return () => abortCont.abort();
 }, []) 
 }

The structure of the returned data.value (after json()-Parsing) you can see here structure of parsed data.value

How can I assign the first element of returned “json()” value to an variable?
Later on I want to pass this “data” variable to another page and work with these values in gatsby.

Pseudocode:

// assign first element to a variable
const aenderungsdatum = data[0].aenderungsdatum

Exception Filter Nestjs not working on my websocket gateway

I’m using the lib ws on nestjs to implement a websocket gateway and using a generic exception filter, but, the filter is not working, the exception never callback the filter.

this is my filter, located in ws-exception.filter.ts

import { Catch, ArgumentsHost } from '@nestjs/common'
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets'
import { WebSocket } from 'ws'

@Catch()
export class WebSocketExceptions extends BaseWsExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        console.log('AAAAAAAAAAAAAAAAAAAAMEn')
        /*
        const ws = host.switchToWs().getClient<WebSocket>()
        ws.terminate()*/
        //super.catch(exception, host)
    }
}

this is my websocket gateway calling the exception, but without callback on the filter


import {                                                                                                                                                                                                             
    OnGatewayConnection,                                                                                                                                                                                             
    OnGatewayDisconnect,                                                                                                                                                                                             
    WebSocketGateway,                                                                                                                                                                                                
    WsException,                                                                                                                                                                                                     
} from '@nestjs/websockets'                                                                                                                                                                                          
import { IncomingMessage } from 'http'                                                                                                                                                                               
import { WebSocket } from 'ws'                                                                                                                                                                                       
import { UseFilters } from '@nestjs/common'                                                                                                                                                                          
import { WebSocketExceptions } from '../ws-exception.filter'                                                                                                                                                         
import { verify } from 'jsonwebtoken'                                                                                                                                                                                
import { config } from 'src/config'                                                                                                                                                                                  

    //extends wsg
@WebSocketGateway({ path: '/ws/operator' })
@UseFilters(new WebSocketExceptions())
export class WsOperatorServiceGateway
    implements OnGatewayConnection, OnGatewayDisconnect
{
    handleConnection(client: WebSocket, req: any) {
        console.log('connecting')
        this.auth(req)
    }

    handleDisconnect(client: any) {
        console.log('disconnectign')
    }

    private auth(req: IncomingMessage): any {
        const token = this.extractTokenFromHeader(req)

        if (!token)
            throw new WsException('No Token')
         

        return verify(token, config.serviceSecret)

    }

    private extractTokenFromHeader(req: IncomingMessage): string | undefined {
        const [type, token] = req.headers.authorization?.split(' ') ?? []
        return type === 'Bearer' ? token : undefined
    }
}

Sorry if my question is stupid, I started a short time ago in nestjs

I hope to be able to call the filter if the exception is sent

Calling useFetch() in Nuxt 3 causes Vue Router error in Docker container

Unfortunately, I can’t trace under what circumstances this started.
But when I try to run it in Docker, errors appear in the console, and the application does not respond to requests.

Nuxt 3.10.2
Docker: 25.0.3

Essence:
Running the application on my host, npm run dev, the application works, there are no errors.
But if I run the application in a docker container, then all useFetch requests throw a Vue Router error:

> docker-compose -f docker-compose.local.yml up
[+] Running 1/2нение пакетного файла [Y(да)/N(нет)]?
 ✔ Network frontend    Created                                                                                     0.1s
 - Container frontend  Created                                                                                     0.2s
Attaching to frontend
frontend  |
frontend  | > dev
frontend  | > nuxt dev
frontend  |
frontend  | Nuxt 3.10.2 with Nitro 2.8.1
frontend  |
frontend  | [QR code]
frontend  |
frontend  |   ➜ Local:    http://0.0.0.0:/
frontend  |   ➜ Network:  http://172.19.0.4:/ [QR code]
frontend  |   ➜ Network:  http://172.20.0.2:/
frontend  |
frontend  | [nuxt:tailwindcss] ℹ Using default Tailwind CSS file
frontend  | ℹ Compiled types/plugins.d.ts in 774.5ms
frontend  | ℹ Compiled plugins/server.mjs in 769.24ms
frontend  | ℹ Compiled plugins/client.mjs in 798.45ms
frontend  | ℹ Vite server warmed up in 76990ms
frontend  | ℹ Vite client warmed up in 82499ms
frontend  | [nitro] ✔ Nitro built in 4538 ms
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"
frontend  | [Vue Router warn]: No match found for location with path "/api/v1/user/profile"

Javascript

     //// file: ./plugins/loadCity.ts
    import {useCityStore} from "~/store/useCityStore";
    
    export default defineNuxtPlugin(async (nuxtApp) => {
        const location = useCityStore();
    
        if(!location.currentCity){
            await location.fetchCity(); // Error: No match found for location with path "/api/v1/city/get"
        }
    });
    
    
    
    
    //// file: /store/useCityStore.ts
    import { defineStore } from "pinia";
    
    export const useCityStore = defineStore('location', () => {
        async function fetchCity() {
            const {data} = await useApiFetch(`/api/v1/city/get`);
    
            // other code
        }
        return { fetchCity }
    });
    
    
    
    //// file: useApiFetch.ts
    export function useApiFetch<T> (path: string|(() => string)|ComputedRef<string>, options: UseFetchOptions<T> = {}) {
        const config = useRuntimeConfig()
    
        const xsrfToken = useCookie('XSRF-TOKEN');
    
        let headers: any = {
            accept: 'application/json',
            referer: config.public.api.referer,
            ...options?.headers,
        }
    
        if (xsrfToken && xsrfToken.value !== null) {
            headers['X-XSRF-TOKEN'] = xsrfToken.value as string;
        }
    
        if (process.server) {
            headers = {
                ...headers,
                ...useRequestHeaders(['cookie']),
            }
        }
    
        return useFetch(path, {
            baseURL: config.public.api.url,
            watch: false,
            credentials: 'include',
            ...options,
            headers,
        })
    }

Dockerfile

# syntax = docker/dockerfile:1

ARG NODE_VERSION=20.9

FROM node:${NODE_VERSION}-slim as base

ENV NODE_ENV=development

WORKDIR /src

# Build
FROM base as build

COPY --link package.json package-lock.json ./

RUN npm install

# Run
FROM base

COPY --from=build /src/node_modules /src/node_modules

CMD [ "npm", "run", "dev" ]

Docker compose yml:

version: '3.7'
services:
  frontend:
    container_name: frontend
    build:
      context: .
      dockerfile: ./Dockerfile.dev
    restart: always
    volumes:
      - ./:/src
      - node_modules:/src/node_modules
    working_dir: /src
    expose:
      - 80
      - 24678
    ports:
      - "24678:24678"
    environment:
      NODE_OPTIONS: '--max_old_space_size=4096'
      VIRTUAL_HOST: $FRONTEND_DOMAIN
      LETSENCRYPT_HOST: $FRONTEND_DOMAIN
      LETSENCRYPT_EMAIL: "[email protected]"
      HTTPS_METHOD: noredirect
      VIRTUAL_PORT: 80
      NITRO_PORT: 80
      NITRO_HOST: 0.0.0.0
      PORT: 80
      NUXT_SITE_URL: $NUXT_SITE_URL
      NUXT_API_URL: $NUXT_API_URL
      NUXT_API_REFERRER: $NUXT_API_REFERRER
      NUXT_SEARCH_API_KEY: $NUXT_SEARCH_API_KEY
      NUXT_SEARCH_HOST: $NUXT_SEARCH_HOST
      NUXT_SEARCH_PORT: $NUXT_SEARCH_PORT
      NUXT_SEARCH_PROTOCOL: $NUXT_SEARCH_PROTOCOL
    networks:
      - frontend
      - reverse-proxy

networks:
  reverse-proxy:
    name: reverse-proxy
    external: true
  frontend:
    name: frontend
    driver: bridge

volumes:
  node_modules:

There was an assumption that the problem was a proxy, and requests to the api were sent not to the backend, but to the nuxt application.
But if you just raise the container, without a proxy, and send an http request directly to the container, then the error repeats.

Programmatically downloading a file doesn’t work only for CSV/Text files [closed]

I’m using this code to programmatically download files in the client (browser).

const download = () => {
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.style.display = "none";
    a.href = file; // file is a blob url
    a.download = originalName; // this includes extension
    a.click();
  };

This works for every file type except text and csv files which I guess are also text files.

In these cases, the contents of the file become HTML and the actual contents are not there. The downloaded file looks something like this:

<!DOCTYPE html>
<html>
  <head>
    <style data-next-hide-fouc="true">
      body {
        display: none;
      }
    </style>
    // bunch of react related script tags here
  </body>
</html>

Browser: Edge Version 123.0.2420.97

OS: macOS Sonoma 14.4.1 (23E224)

Syncing state between two or more browser tabs

Logic in my app is that I update something in settings page and after it is successfully updated I mutate user data which is used in further requests (like creating order with users chosen currency etc.). But if I update in one browser tab I am still able to go to another tab(which was opened before mutating user) and try to create order request is sent using redundant code (field in user entity). Is there a native way to sync tabs ?

Alguien me recluta?

mi nombre es Juan Esteban, soy de Colombia y tengo 23 años. Estoy acá porque quiero saber si conocen alguna empresa o persona que esté reclutando personas interesadas en aprender de manera profesional y con proyectos reales programación. Conozco las bases de programación orientada a objetos, conozco los conceptos básicos de Python, Java, JavaScript, HTML, CSS, SQL. Pero me gustaría saber si alguna empresa o persona que tenga interés en formarme, darme una guía en otras palabras, introducirme de manera profesional a este mundo de la programación. Sé que en internet se encuentra demasiada información (la cual en mi ignorancia he aprovechado formándome empíricamente), pero a veces la información es tanta que me disperso, no sé por dónde seguir, como avanzar, como aportar en proyectos reales etc.
Gracias si llegaste hasta acá y leíste mi mensaje.

Alguien que conozca de algún reclutador que enseñe programación gratis de manera profesional

The playwright-python is clickable but nothing happen

with sync_playwright() as p:
     browser = p.chromium.launch(headless=False, slow_mo=50)
     page = browser.new_page()
     page.goto('https://ctrl.unruly.co/auth/login')
     page.fill('input[id="email"]', username)
     page.fill('input[id="password"]',password)
     result = solveRecaptcha(
         sitekey=sitekey,
         url=url
     )
     code = result['code']
        
     page.evaluate(f"""() => {{
         var token = '{code}';
         var callbackFunction = ___grecaptcha_cfg.clients['0']['F']['F']['callback'];
         callbackFunction(token);

     }}""")
     page.wait_for_selector("button#submit:not([disabled]):not([tabindex])",state='attached')

     page.screenshot(path="debug_screenshot.png")

     page.click('button#submit:not([disabled]):not([tabindex])')

     page.screenshot(path="debug_screenshot2.png")

This is my script using playwrigth-python, the website has a recaptcha callback. I bypass all of those flawlessly, the ‘Sign In’ button appear but it is unclickable. Actually it is clickable because when I run the script with ‘headless=false’, I saw that it is performing the ‘page.click’ but it did not go to the homepage. Usually if we press the sign in button it will immediately go to the homepage of the website.

The element before the sign in button appear are shown like this:

<button _ngcontent-ng-c3870558994="" nz-button="" nzsize="large" nztype="primary" nzblock="" id="submit" class="ant-btn primary-button ng-tns-c630436078-2 ant-btn-primary ant-btn-lg ant-btn-block" tabindex="-1" disabled="true"><!----><span class="ng-star-inserted"> Sign In </span></button>

And the element after the sign in button appear are shown like this:
<button _ngcontent-ng-c3870558994="" nz-button="" nzsize="large" nztype="primary" nzblock="" id="submit" class="ant-btn primary-button ng-tns-c630436078-2 ant-btn-primary ant-btn-lg ant-btn-block"><!----><span class="ng-star-inserted"> Sign In </span></button>

As you can see the two attributes in the HTML will be deleted once the sign in button appear, the 2 attributes tabindex="-1" disabled="true".

I feel like Ive done correctly, but I need some one pov on this. Your help will be mush appreciated. I will provide the snapshots.

this image show that the sign in button appear (dark blue colour)
This image show that the page.click in action (slightly pale dark blue) but I feel like it is not clicking

Once you click it will go to the homepage but this is not doing that.

I tried to put page.goto(to the homepage) under the page.click but it kick me back to the login page

Vue 3 + Vite and WebRTC struggling on setting things up

I was using Vite + Vue 3 and decide to make a video streaming application, I followed the tutorial, and even the official document to install the package vue-webrtc, but when I import it, it logged an error ‘global is not defined‘, so I define it in vite.config.js as

define: {
global: {},
},

now, the error change to ‘Buffer is not defined‘, I did a research around the web to see if anyone is having the same trouble as me, found an answer on stackoverflow saying that this package is built on webpack and is not vue 3 friendly. Is anyone having the same issue and have you found the solution ?

also when I install the package, it says [email protected]: core-js@<3.23.3 and [email protected] is deprecated, so I tried to install the newest versions, but it does not work.

It also showed a TS warning that ‘Could not find a declaration file for module ‘vue-webrtc’. ‘/home/ayakase/Documents/vuewebrtc/node_modules/vue-webrtc/dist/vue-webrtc.ssr.js’ implicitly has an ‘any’ type.’

but I’m using JS so I suppose that I could just skip this warning.

Need Assistance Removing Malware from FastComet Hosted Websites [closed]

I have six websites hosted on FastComet, and all of them have been infected with malware, resulting in white pages being displayed. I’ve contacted FastComet, but they were unable to assist with malware removal.

What steps can I take to remove the malware from my websites and restore them to normal operation? Are there any specific tools or techniques I should use? Any advice or guidance would be greatly appreciated.

Thank you!

I’ve tried scanning my websites for malware using online tools like Sucuri SiteCheck and VirusTotal, but they didn’t detect any issues. I also reached out to FastComet support, but they couldn’t help with malware removal. I was expecting the scanning tools to identify and remove any malware present on my websites. What additional steps can I take to effectively remove the malware and restore my websites?

Issues with multi line chart D3 V7

I am creating a multi-line chart using D3v7. Finished my code but no lines are showed and scale for xAxis doesn’t work.
I am unable to figure out the reason for the these issues.

This is my data: adidas_west_sales.csv

enter image description here

My code:

            const width = 800;
            const height = 500;
            const paddingLeft = 60;
            const paddingRight = 50;
            const paddingTop = 50;
            const paddingBottom = 50;
            
            const graphWidth = width - (paddingLeft + paddingRight);
            const graphHeight = height - (paddingTop + paddingBottom);
            
            // Setup SVG
            var svg = d3.select("body").append("svg")
                .attr("width", width + paddingLeft + paddingRight)
                .attr("height", height + paddingTop + paddingBottom)
                .append("g")
                .attr("transform",
                      "translate(" + paddingLeft + "," + paddingTop + ")");
    

// Setup scales

var x = d3.scaleTime().range([0, width]);
        var y = d3.scaleLinear().range([height, 0]);
        var colourScale = d3.scaleOrdinal(d3.schemeCategory10);

//Line generator

var line = d3.line()
        .x(function(d) {return x(d.monthyear); 
        })
        .y(function(d) { return y(d.total); });
  

// Load data

d3.csv('adidas_west_sales.csv').then(buildLineChart);

var parseTime = d3.timeParse("%Y-%m");

function buildLineChart(data)
{
    data.forEach(function(d)
    {
        var monthYear = parseTime(d.MonthYear);
        d.MonthYear = d3.timeFormat("%m-%Y")(monthYear);
    })

    var salesMethods = data.columns.slice(1).map(function(method)
    {   
        return {    method: method,
                    values: data.map(function(d) {
                        return {    monthyear: d.MonthYear,
                                    total: parseFloat(d[method])
                                }
                            }
                )}   
    });      
    

// Setup scales with data

x.domain(d3.extent(data, function(d) {
    return d.MonthYear;}));

y.domain([
    d3.min(salesMethods, function(b) {
        return d3.min(b.values, function(d) {
            return d.total;
        });
    }),
    d3.max(salesMethods, function(b) {
        return d3.max(b.values, function(d) {
            return d.total;
        });
    })
]);

colourScale.domain(salesMethods.map(function(c) { return c.method}))
// Add Axis
svg.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

svg.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y))
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", "0.71em")
    .attr("fill", "#000")
    .text("Total Sale, $");

// Add lines

const lineGraph =
svg.selectAll("path")
      .data(salesMethods)
      .enter()
          .append("path")
          .attr('stroke', function(d, i) { return colourScale(i)})
          .attr('stroke-width', 1.25)
          .style("fill", "none")
          .attr("d", function(d) { return line(d.values); });
   

I got one error for this line: .attr("d", function(d) { return line(d.values); });

*[Error] Error: Problem parsing d="MNaN,353.742LNaN,418.225LNaN,499.291LNaN,382.391LNaN,382.391LNaN,382.391LNaN,382.391LNaN,382.391LNaN,394.082LNaN,382.391LNaN,0LNaN,213.216LNaN,335.469LNaN,212.08LNaN,91.984LNaN,375.627LNaN,368.281LNaN,387.824LNaN,423.087LNaN,436.769LNaN,408.033LNaN,401.896"
            (anonymous function) (d3.v7.min.js:2:18259)
            each (d3.v7.min.js:2:25665)
            buildLineChart (WestRegion.js:105)*

Any help would be greatly appreciated!

NextJS web scrapper is getting duplicate results Amazon product listing

I’m following a tutorial @1:27:20 this

Whenever I’m retrieve the Amazon Product price I get [currentPrice: ‘1799.1781.1799.’] it should be [1799]

import axios from "axios";
import * as cheerio from 'cheerio';
import { extractPrice } from "../utils";

export async function scarpeAmazonProduct(url: string) {

    // BrightData proxy config
    const username = String(process.env.BRIGHT_DATA_USERNAME)
    const password = String(process.env.PASSWORD)
    const port = 22225;
    const session_id = (1000000 * Math.random()) | 0;
    const options = {
        auth: {
            username: `${username}-session-${session_id}`,
            password,
        },
        host: 'brd.superproxy.io',
        port,
        rejectUnauthorized: false
    }

    try {
        // Fetch the product page
        const response = await axios.get(url, options);
        const $ = cheerio.load(response.data);
        
        // Extract Product title
        const title = $('#productTitle').text().trim();
        
        const currentPrice = extractPrice(
            $('.priceToPay span.a-price-whole'),
            $('.a.size.base.a-color-price'),
            $('.a-button-selected .a-color-base'),
            $('span.a-price.a-text-price'),
        );

        console.log({ title, currentPrice });
    } catch (error: any) {
        throw new Error(`Failed to scrape product: ${error.message}`)
    }
}
export function extractPrice(...elements: any) {
    for (const element of elements) {
        const priceText = element.text().trim();

        if (priceText) return priceText.replace(/[^d.]/g, '');
    }

    return '';
}

I’ve tried various selector tags only as to not stray too far from tutorial.

Axios Error During Logout? Response shows Unauthorized Access

error photo

in my MERN project why its show axios error and in response i get unauthorize token in deployment but it perfectly work on postman and in development.
i want logout successful but it doesn’t work all other like login, upload blog , delete and update blog work..

/* eslint-disable no-unused-vars */
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import Cookies from "universal-cookie";
import { useNavigate } from "react-router-dom";
import { removeUser } from "../Redux/Slices/userSlice";
import { SERVER } from "../../utils/Constant";

const Header = () => {
  const { user } = useSelector((store) => store.user);
  // console.log(user);
  const [showMenuBtn, setShowMenuBtn] = useState(true);
  const handleMenu = () => {
    setShowMenuBtn(!showMenuBtn);
  };
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const cookies = new Cookies();
  const api = axios.create({
    baseURL: SERVER,
    withCredentials: true,
  });
  // const accessToken = sessionStorage.getItem("accessToken");
  // console.log(accessToken);
  const handlesignOut = async () => {
    try {
      await api.post("/api/v1/users/logout", {});
      dispatch(removeUser());
      localStorage.removeItem("username");
      navigate("/");
      const cookieKeys = Object.keys(cookies.getAll());
      cookieKeys.forEach((key) => {
        cookies.remove(key);
      });
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };
  return (
    <div>
      ....
      </div>
  );
};

export default Header;

————-this is the conroller for my logout—————-

const logOutUser = AsyncHandler(async (req, res) => {
  await User.findByIdAndUpdate(
    req.user._id,
    {
      $unset: {
        refreshToken: 1,
      },
    },

    {
      new: true,
    }
  );

  const options = {
    httpOnly: true,
    secure: true,
  };
  return res
    .status(200)
    .clearCookie("accessToken", options)
    .clearCookie("refreshToken", options)
    .json(new ApiResponse(200, "user loggedOut successfully"));
});

——————-router for logout————–

import Router from "express";
import {
  registerUser,
  logInUser,
  logOutUser,
} from "../controllers/user.controller.js";
import { verifyJWT } from "../middlewares/auth.middleware.js";

const userRouter = Router();

userRouter.route("/register").post(registerUser);
userRouter.route("/login").post(logInUser);

userRouter.route("/logout").post(verifyJWT, logOutUser);

export { userRouter };

——-verify jwt middleware—————

import { AsyncHandler } from "../utils/AsyncHandler.js";
import { ApiError } from "../utils/ApiError.js";
import jwt from "jsonwebtoken";
import { User } from "../models/user.model.js";

const verifyJWT = AsyncHandler(async (req, _, next) => {
  try {
    const token =
      req.cookies?.accessToken ||
      req.header("authorization")?.replace("Bearer ", "");

    if (!token) {
      throw new ApiError(400, "UnAutherized access");
    }

    const decodedToken = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
    const user = await User.findById(decodedToken?._id).select(
      "-refreshToken -password"
    );
    if (!user) {
      throw new ApiError(401, "invalid accessToken");
    }
    req.user = user;
    next();
  } catch (error) {
    throw new ApiError(400, error?.message || "invalid accessToken");
  }
});

export { verifyJWT };

Trying to check highlight my current selected navbar item by matching window.Location.pathname to the NavLink to=

I don’t know how to reference the NavLink’s to field in my li element, so I can check if the current route is the same as what its navigating to.

In theory this is how I would imagine it works.

const getElementPath = (ele) => {
  return ele.NavLink.to
  };  
return (   
   <nav class="grey darken-4">
     <div className="nav-wrapper nav-center">
         <ul className="center">
            <li class={getElementPath(currentElement) === window.Location.pathname ? 'active' : '' }><NavLink to="/">Home</NavLink></li>

I tried using this, but of course that is looking at my Component, and not the current element.

Infer React child props in TypeScript interface

Is it possible to infer the props of the first child element and enforce them in TypeScript? I can get it close, but it begins to fail with generics, and I haven’t been able to infer the type.

I’m trying to pass component props from a wrapper to the first child component with type-safety. When the prop doesn’t exist on the object, TS should fail, otherwise pass.

import React, { Children, isValidElement, cloneElement, ReactNode } from 'react';

interface WrapperProps<C> {
    children: ReactNode;
    // how can I make typeof Button generic/inferred from the code?
    // firstChildProps: Partial<React.ComponentProps<typeof Button>>; // works with <C> removed
    firstChildProps: Partial<React.ComponentPropsWithoutRef<C>>;
}

const Wrapper: React.FC<WrapperProps<typeof Button>> = ({ children, firstChildProps }) => {
    const firstChild = Children.toArray(children)[0];
    if (isValidElement(firstChild)) {
        // Clone the first child element and pass the firstChildProps to it
        return cloneElement(firstChild, { ...firstChildProps });
    } else {
        return <>{children}</>;
    }
}

interface ButtonProps {
    disabled: boolean;
    children: ReactNode;
}

const Button: React.FC<ButtonProps> = ({ disabled, children }) => {
    return <button disabled={disabled}>{children}</button>;
}

const Example = () => {
    return (
        <>
            {/* Passes type check because disabled exists on Button */}
            <Wrapper firstChildProps={{ disabled: false }}>
                <Button disabled={true}>Ok</Button>
            </Wrapper>
            {/* Fails type check because cheese does not exist on Button */}
            <Wrapper firstChildProps={{ cheese: true }}>
                 <Button disabled={true}>Ok</Button>
            </Wrapper>
        </>
    );
}

Here’s a nearly working TS Playground.