Tapping into create-react-app compilation flow

Is it possible to detect the start and end of compilation in a create-react-app + TypeScript project during development active session?

I am willing to modify underlying node modules for local testing purposes.
When I save a source file during a debug session, My goal is to call a web API on start and end of compilation and log the time it takes for the updates to be reflected after compilation and fast refresh/hot reload.

Rendering single data from an array using .find()

I am trying to display single details of an object inside an array using .find() but I keep getting undefined.

Below is my code on what I was trying to do, when I log id, i get the value but when i log service i get undefined. what could be wrong

import React from "react";

import { useParams } from "react-router-dom";

import { services } from "../constants";

const ServiceDetails = () => {
  const { id } = useParams();

  const service = services.find((item) => item.id === id);

  console.log(id);

  return (
    <div>
      <h2 className="h2 text-accent font-secondary text-[30px] lg:text-[55px]">
        {service?.title}
      </h2>
    </div>
  );
};

export default ServiceDetails;

React Testing: Open Modal click event error — ‘pointer-events: none’

I have a React test failing and I while I think I know why it’s failing, I am not sure how to fix it. The test should add an item to the Dom (with a click) and remove an item from the Dom (with a click). When the user removes an item, a modal pops up to ensure the user wants to make this action. The test below works up until await user.click(modalButton); The error in the terminal is

Unable to perform pointer interaction as the element has pointer-events: none

I am assuming this is because the test still thinks the modal is hidden and the button within the modal doesn’t have any functionality but I am not sure. If I am right I have no idea how to fix this and if I am wrong, I have no idea what the issue is. I am still learning how to effectively write test so this one is a little over my head. Any suggestions would be greatly appreciated.

it('should remove a item when user clicks (-)', async () => {
    const { getByTestId, queryByTestId, getAllByTestId } = render(
        <App />
    );

    const addBtn = await getByTestId('add');
    expect(addBtn).toBeInTheDocument();
    const removeBtn = await getByTestId('remove');
    expect(removeBtn).toBeInTheDocument();

    const user = userEvent.setup();

    await user.click(addBtn);
    const cardContainer = await queryByTestId('card');

    expect(cardContainer).toBeInTheDocument();
    await user.click(removeBtn);

    expect(getAllByTestId('modal')[0]).toBeInTheDocument();
    const modalButton = getAllByTestId('delete-button')[0];

    await user.click(modalButton);
    expect(cardContainer).not.toBeInTheDocument();
});

Just in case you’re wondering why I am using a getAllByTestId, it is because I actually have two modals hidden and the text inside each is based on a conditional which is checked prior to it opening.

How to interchange an element between 2 arrays?

I’ve been trying to use the splice() and indexOf() methods on javascript for the first time, but I don’t understand the parameters.

I’m trying to make a game. When you click a card, it goes up and goes to another array.
Here is the code, arrays and variables:


var statusc1 = 'down';
let upcards = [];
let downcards = [
    pcard1,
    pcard2,
    pcard3,
    pcard4,
    pcard5
];


pcard1.addEventListener('click', ()=> {
    if(statusc1 == 'down') {
        console.log('its down');
        pcard1.style.bottom = -10;
        statusc1 = 'up';

        upcards.push(downcards[0]);
        downcards.splice(downcards.indexOf(pcard1),1);
        console.log(upcards);
    } else {
        console.log('its up');
        pcard1.style.bottom = -60;
        statusc1 = 'down';

        downcards.push(upcards[0]);
        upcards.splice(downcards.indexOf(pcard1),1);
        console.log(downcards);
    }
})

When it changes array, then goes back to the original one, the element does go back to the initial array (In the last position) but the second array (upcards) also keeps it and for some reason, stores a 2nd card (pcard2).

I tried changing the parameters of the splice method, but I don’t understand them.

How to use the class from added code in the jquery function

I create html code with jquery.

<span id="myspan">aa</span>
<input id="btn" type="button" value="click">

Now I want to call a function created by clicking on the code class.

function loadSpan()
{
var _html = "<a class="addItem">test</a>";
$('#myspan').html(_html);
}
$(function(){
$('#btn').click(function(){
loadSpan();
});
$('.addItem').click(function(){
alert("OK");
});
})

but is not working. I testing this code, and working:

$(function(){
loadSpan();
});

But I want to generate the code after clicking the button.

test code

Change color of selected toggle buttons using MUI ThemeProvider

I’m trying to change the color of selected toggle buttons in an app using React, Typescript, and ThemeProvider from @mui/material 5.11.13.

When a toggle button is selected, it still has color #1976d2, which is the same as MUI’s palette.primary.main color instead of the new theme color.

I’ve tried a few things without success, and the latest code is below. Any idea how to get it working?

import { createTheme, ThemeProvider as MuiThemeProvider } from '@mui/material';

// this didn't work
// import { createTheme, ThemeProvider as MuiThemeProvider } from '@mui/material';

// this didn't work
// import { createTheme, ThemeProvider as MuiThemeProvider } from '@mui/material/styles';

// this didn't work
// import { ThemeProvider as MuiThemeProvider, createTheme } from '@material-ui/core/styles';

const mui5 = {
    palette: {
        primary: {
            main: '#ff0000',
            dark: '#ff0000',
            contrastText: '#ff0000',
        },
        secondary: {
            main: '#ff0000',
            dark: '#ff0000',
            contrastText: '#ff0000',
        },
    },
    components: {
        MuiToggleButton: {
            styleOverrides: {
                root: {
                    '&.Mui-selected': {
                        color: '#000000',
                        background: '#ff0000',
                        backgroundColor: '#ff0000',
                    },
                    '&:hover': {
                        color: '#000000',
                        background: '#ff0000',
                        backgroundColor: '#ff0000',
                    },
                },
            },
        },
    },
};

const muiTheme = createTheme(mui5);

...

<MuiThemeProvider theme={muiTheme}>

GooglePlacesAutocomplete does not register suggestion touches on an Android BottomSheet in React Native

I am trying to implement a feature in my app that allows users to search an address and select a suggestion. I used GooglePlacesAutocomplete to achieve this result. I have the code for autocomplete on a bottom sheet. The code works as intended on iOS but does not register suggestion selections on android.

My code for the bottomsheet component is as follows: (Omitting imports and styles)

const BottomSheet = forwardRef(({ activeHeight, children }, ref) => {
  const { height } = useWindowDimensions();
  const newActiveHeight = height - activeHeight;
  const topAnimation = useSharedValue(height);

  const open = useCallback(() => {
    "worklet";
    topAnimation.value = withSpring(newActiveHeight, {
      damping: 100,
      stiffness: 400,
    });
  }, []);

  const close = useCallback(() => {
    "worklet";
    Keyboard.dismiss();
    topAnimation.value = withSpring(height, {
      damping: 100,
      stiffness: 400,
    });
  }, []);

  useImperativeHandle(
    ref,
    () => ({
      open,
      close,
    }),
    [open, close]
  );

  const animationStyle = useAnimatedStyle(() => {
    const top = topAnimation.value;
    return {
      top,
    };
  });
  const backDropAnimation = useAnimatedStyle(() => {
    const opacity = interpolate(
      topAnimation.value,
      [height, newActiveHeight],
      [0, 0.5]
    );
    const display = opacity === 0 ? "none" : "flex";
    return {
      opacity,
      display,
    };
  });

  const gestureHandler = useAnimatedGestureHandler({
    onStart: (_, ctx) => {
      ctx.startY = topAnimation.value;
    },
    onActive: (event, ctx) => {
      if (event.translationY < 0) {
        topAnimation.value = withSpring(newActiveHeight, {
          damping: 100,
          stiffness: 400,
        });
      } else {
        topAnimation.value = withSpring(ctx.startY + event.translationY, {
          damping: 100,
          stiffness: 400,
        });
      }
    },
    onEnd: (_) => {
      if (topAnimation.value > newActiveHeight + 50) {
        topAnimation.value = withSpring(height, {
          damping: 100,
          stiffness: 400,
        });
      } else {
        topAnimation.value = withSpring(newActiveHeight, {
          damping: 100,
          stiffness: 400,
        });
      }
    },
  });

  return (
    <>
      <TouchableWithoutFeedback
        onPress={() => {
          close();
        }}
      >
        <Animated.View style={[styles.backDrop, backDropAnimation]} />
      </TouchableWithoutFeedback>
      <PanGestureHandler onGestureEvent={gestureHandler}>
        <Animated.View style={[styles.container, animationStyle]}>
          <View style={styles.lineContainer}>
            <View style={styles.line} />
          </View>
          {children}
        </Animated.View>
      </PanGestureHandler>
    </>
  );
});

export default BottomSheet;

My code for where the BottomSheet being triggered is as follows:

     const ref = useRef();
     const onPress = useCallback(() => {
       ref.current.open();
     }, []);


   <Pressable style={styles.otherContainer} onPress={onPress}>
       <Text style={styles.header}>Location</Text>
       <CustomIcon name="Pin" width={35} height={35} />
   </Pressable>


     <BottomSheet
        style={styles.location}
        ref={ref}
        activeHeight={height * 0.87}
      >
        <LocationDropdown style={styles.locationDropdown} />
      </BottomSheet>

Finally, my code for the GooglePlacesAutoComplete (LocationDropdown) is as follows:

import React, { useState } from "react";
import {
  View,
  LayoutAnimation,
  StyleSheet,
  TouchableOpacity,
  Text,
  UIManager,
  KeyboardAvoidingView,
} from "react-native";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
import Colors from "../../../../utils/colors";

if (
  Platform.OS === "android" &&
  UIManager.setLayoutAnimationEnabledExperimental
) {
  UIManager.setLayoutAnimationEnabledExperimental(true);
}
const LocationDropdown = ({ modalWidth, modalHeight, ...props }) => {
  const [searchPosition, setSearchPosition] = useState("minimized");

  // TODO: Key should not be stored here

  return (
    <View style={{height:500}}>
      <GooglePlacesAutocomplete
        placeholder="Where is your event?"
        onPress={(data, details = null) => {
          console.log(data, details);
        }}
        query={{
          key: "API_KEY",
          language: "en",
        }}
        fetchDetails={true}
        styles={{
          textInputContainer: {
            marginTop: 10,

          },
          textInput: {
            fontFamily: "QuicksandMedium",
            color: "black",
          },
          // placeholder: {
          //   color: "black",
          // },
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  searchContainer: {
    alignSelf: "center",
    backgroundColor: Colors.primary500,
  },
});

export default LocationDropdown;

On the android side, the auto complete places show up, but the touches are not being registered and data is not being logged to the console.
Thanks in advance!

Impact of Vpn/proxy on timezone of browser, android and ios device

I wanted to understand how does usage of proxy or VPN impact local timezone of a browser, android and ios device.
For example –

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(tz);

While testing this on my browser using VPN, the result was the same for different VPN regions. So, I guess the usage of VPN does not impact the browser timezone.
How do I confirm that usage of VPN will not overwrite this parameter ? I could not find much info on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl to know from where is the timezone parameter is derived.

TimeZone.getDefault().getDisplayName()

The timezone is obtained via System properties – https://docs.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29 . Will a VPN overwrite these properties ?

TimeZone.current.identifier

As per https://developer.apple.com/documentation/foundation/timezone , it is the current timezone used by the system. Will a VPN overwrite it ?

And if above way is not reliable, what is a reliable way to know the correct local timezone of a android device, ios device and browser.

What is the error in the implementation of the native messaging using chrome extension and powershell script as native app

I try to make simple chrome extension that takes active directory username from input field and send to native app – powershell script – that use active directory module to find username and return his phone and email in JSON.
Now i have error: “Unchecked runtime.lastError: Error when communicating with the native messaging host.”
All the code is below.

manifest.json
 {
   "name": "AD Extension",
   "description": "Get phone and email from AD",
   "version": "1.0",
   "manifest_version": 3,
   "icons": {},
   "permissions": [
     "nativeMessaging",
     "activeTab"
   ],
   "host_permissions": [
     "https://*/*",
     "http://*/*"
   ],
   "action": {
     "default_popup": "popup.html"
   },
   "background": {
     "service_worker": "background.js"
   }
 }
popup.html
<!DOCTYPE html>
<html>
  <head>
    <title>AD Extension</title>
    <script defer src="background.js"></script>
  </head>
  <body>
    <label for="username">Enter AD username:</label>
    <input type="text" id="username" name="username"><br>
    <button id="get-info">Get Phone and Email</button>
    <div id="info"></div>
  </body>
</html>
popup.js
document.addEventListener("DOMContentLoaded", function () {
const button = document.getElementById("get-info");
button.addEventListener("click", function () {
const username = document.getElementById("username").value;
chrome.runtime.sendNativeMessage(
            "com.smm.adextension",
command: "get_user_info", username: username },
function (response) {
//Parse the JSON output into a JavaScript object
const outputObj = JSON.parse(response);
console.log(outputObj);
//Access the phone and email properties of the output object
const phone = outputObj.phone;
const email = outputObj.email;
console.log(phone, email);
const infoDiv = document.getElementById("info");
console.log(infoDiv);
infoDiv.innerHTML = "Phone: " + phone + "<br>Email: " + email;
            }
        );
    });
});
background.js
const port = chrome.runtime.connectNative('com.smm.adextension');
port.onMessage.addListener(function(request, sender, sendResponse) {
if (request.command === "get_user_info") {
chrome.runtime.sendNativeMessage(
        "com.smm.adextension",
command: "get_user_info" },
function(response) {
console.log(response);
sendResponse(response);
        }
      );
    }
return true;
  });
nativeapp.json
{
    "name": "com.smm.adextension",
    "description": "Native messaging app for AD Extension",
    "path": "./nativeApp.ps1",
    "type": "stdio",
    "allowed_origins": [
      "chrome-extension://dhfgiijbgbcpjinfhhhlniaegdjpldbm/"
    ]
  }
nativeapp.ps1
//Import the ActiveDirectory module
Import-Module ActiveDirectory

//Retrieve the phone number and email address for the specified user
$user = Get-ADUser -Identity $args[0] -Properties telephoneNumber, emailAddress

$phone = $user.telephoneNumber

$email = $user.emailAddress

//Create a PowerShell object containing the phone and email values
$output = @{ phone = $phone; email = $email }


//Convert the object to JSON format and write it to standard output
$outputJson = ConvertTo-Json $output
Write-Output $outputJson

I added path to native app with its name in registry.
allowed_origins field in the nativeApp.json file matches the ID of the extension.

iam trying to create a delete current user method but the findById method return null always

iam trying to create a deleteCurrentUser Method by gitting the currentUser token and decode it and get the id and find the user by this decoded it , but when i try to get the currentUser data by using findById method it always return null and i dont know why


This is the code

exports.deleteUser = catchAsync(async (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
    console.log(decoded); // check the decoded value

    const currentUser = await User.findById(decoded.id);
    console.log(decoded.id)
    console.log(currentUser); // check the currentUser value

    if (!currentUser) {
      return next(new AppError('User not found', 404));
    }

    if (currentUser._id.toString() !== req.params.id) {
      return next(new AppError('This account does not belong to you', 401));
    }

    await User.findByIdAndDelete(currentUser._id);

    res.status(200).json({
      status: 'Success',
      message: `User ${req.params.id} has been deleted successfully`,
    });
  } catch (err) {
    return next(err);
  }
});

and this is the route

router
  .route('/:id')
  .delete(userController.deleteUser);

i have tried to use findOne

findOne({ _id: decoded.id });

insted of using findById , and it still gives me null


note

decoded.id gives me the right userID and req.params.id also gives me the right id and they are the same when i tried consol.log

tailwind and javascript phone responsive bottom tab issue

So i open a page on my mobile phone.
And the phone its self has a popup bar of navigation options.
Which means if i load a page set at screen height. Some of it actually disappears behind this bar.
Im trying to find a way to automatically calculate any bar any phone or browser might throw at you. Im currently just using a calc method. But its always off by a pixel or two

 function SendNewMessage() {
 return (
  <section className='grid h-[calc(100vh-98px)] lg:h-screen lg:grid-rows-reg 
   overflow-hidden border-2 border-black border-solid w-full'>
  <div className='w-full'>
    <Navbar />
  </div>
   SendNewMessage
  </section>
  );
 }

Cant figure out leaflet in NextJS (react-leaflet)

So basicaly i just want to dispaly a simple leaflet map in my NextJS map. The problem is that the div in wich i want to display the map stays empty (I set the .leaflet-container height wnd width to 100%)

My Map Component:

import { TileLayer, Marker, Popup, MapContainer } from "react-leaflet";
import s from "../../styles/Admin.module.scss";
import "leaflet/dist/leaflet.css";

export default function Map({}: {}) {
  return (
    <div className={s.leaflet} id="map">
      <MapContainer
        center={[51.505, -0.09]}
        zoom={13}
        style={{ height: "100%", width: "100%" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[51.505, -0.09]}>
          <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
          </Popup>
        </Marker>
      </MapContainer>
    </div>
  );
}

I includet the following in my _document.tsx

          <link
            rel="stylesheet"
            href="https://unpkg.com/[email protected]/dist/leaflet.css"
            integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          />
          <script
            src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
          ></script>

I am loading the Map component “dynamic”

const Map = dynamic(() => import("../Components/Map"), {
    ssr: false,
  });

I have tries everything i fond and ran out of thing to try so id appreciate if you could help me out

Filter from a drop-down list?

I would like to create a dropdown list that filters multiple items based on the STATUT variable

enter image description here

TOUS   = 0 
ENCORE = 1
ANNULE = 8
FAIT   = 9

I show you the inferface

export interface TransferResponse extends ApiResponse {
    PRE: Transfer[];
}

export interface Transfer {
    DEPO: number;
    CLER: string;
    INTITULE1: string;
    PHONE: string;
    PREPTF: {
        LABEL: string;
        TYPE: string;
        QUANTITE: number;
        STATUT: number; /* Variable  to filter */ 
        NUM: number;
        ISIN: string;
        STATUT_LIB: string;
        REF_RBC: string;
    }[];
}

The template

<div class="card" *ngIf="currentAgency">
   <div class="card-body">
      <form #formulaire="ngForm" >
         <div class=" row mb-4 align-items-end ">
            <div class="col-12 col-sm-6 col-md-4">
               <div class="mb-2">
                  <h5>Sélectionnez un item </h5>
                  <select id="item-select" class="form-select form-max-width" [(ngModel)]="selectedStatut" (change)="onChangeStatut($event)">
                  <option selected disabled value="">Sélectionnez un item</option>
                  <option [value]="''">TOUS</option>
                  <option [value]="'1'">ENCODE </option>
                  <option [value]="'8'">ANNULE</option>
                  <option [value]="'9'">FAIT</option>
                  </select>
               </div>
            </div>
         </div>
      </form>
      <br>
      <table class="table table-bordered table-striped table-hover">
         <thead>
            <tr class="text-center">
               <!-- DEPO -->
               <th>DEPO</th>
               <!-- STATUT  -->
               <th>STATUT</th>
            </tr>
         </thead>
         <tbody>
            <ng-container *ngFor="let transfer of transferResponse.PRE">
               <ng-container *ngFor="let preptf of transfer.PREPTF">
                  <tr>
                     <td class="text-start">
                        <a class="link-primary" role="button">
                        {{ transfer.DEPO  }} 
                        </a>
                     </td>
                     <ng-container *ngIf="preptf.STATUT === 1">
                        <td class="text-center">{{preptf.STATUT_LIB}}</td>
                        <td class="text-center py-1">
                           <!-- Annuler -->
                           <button (click)="onDeletePreptf(preptf)" class="btn btn-success outline btn-xs"> Annuler</button>
                        </td>
                     </ng-container>
                     <ng-container *ngIf="preptf.STATUT === 8">
                        <td class="text-center">{{preptf.STATUT_LIB}}</td>
                        <td class="text-center py-1">
                        </td>
                     </ng-container>
                     <ng-container *ngIf="preptf.STATUT === 9">
                        <td class="text-center">{{preptf.STATUT_LIB}}</td>
                        <td class="text-center py-1"></td>
                     </ng-container>
                  </tr>
               </ng-container>
            </ng-container>
         </tbody>
      </table>
   </div>
</div>

My problem is that when I select an item, for example FAIT (Statut=9)

enter image description here

After selecting an item, the filter does not run. I share you some consoles.log.

enter image description here

Honestly, I don’t know how to make my filter work? Do you have a solution please?

composent

export class OverviewTransfersComponent implements OnInit, OnDestroy {
   private unsubscribe$ = new Subject < void > ();

   currentAgency: any;
   transferResponse: TransferResponse;
   account: string;

   selectedStatut;

   filteredTransfers: Transfer[] = [];

   constructor(
      private service: OverviewTransfersService,
      private store: Store,
      private modalService: BsModalService,
      private router: Router


   ) {
      this.account = '';
      this.selectedStatut = ''; // initialization of the selectStatus variable
   }

   ngOnInit(): void {
      this.currentAgency = this.store.selectSnapshot(AgencyState.currentAgency);
      if (this.currentAgency) {
         this.overviewTransfers(this.account);
      }
   }

   ngOnDestroy(): void {
      this.unsubscribe$.next();
      this.unsubscribe$.complete();
   }

   overviewTransfers(account: string): void {
      this.service.overviewTransfers(account).pipe(
         takeUntil(this.unsubscribe$)
      ).subscribe(res => {
         if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
            this.transferResponse = res as TransferResponse;
            console.log("data => ", this.transferResponse);

         }

      });
   }

   filterByStatut(): void {
      console.log("Before filter :", this.transferResponse.PRE);
      if (this.transferResponse && this.transferResponse.PRE && this.selectedStatut) {
         this.filteredTransfers = this.transferResponse.PRE.filter((transfer) =>
            transfer.PREPTF.some((preptf) => preptf.STATUT === this.selectedStatut)
         );
      } else {
         this.filteredTransfers = this.transferResponse.PRE || [];
      }
      console.log("After filter :", this.filteredTransfers);
   }


   onChangeStatut(event: any) {
      this.selectedStatut = event.target.value;
      console.log("Selected value:", this.selectedStatut);
      this.filterByStatut();
   }


}

Thank you four your help.

this happend when im trying to install nodemon “rollbackFailedOptional: verb npm-session 879d4e885aa20cee” it says that it’s a internet issue, I’m new

this happend when im trying to install nodemon “rollbackFailedOptional: verb npm-session 879d4e885aa20cee” it says that it’s a internet issue, I’m new to JS, in the logs it said “error for nodemon@latest request to https://my.registry.com/nodemon” when I open the link It states that it closed the connection. I am so confused, am I dumb???

I tried different ways to install nodemon with yarn.

variable undefined when console.log before export component React-Native Functional

the problem is this:

I have a global variable (outside componentA definition) let name: string for example, I need to assign a value after fetch it from backend in the useEffect [], and use it before the component is exported, but at that time the variable is undefined, there is any way to do it or something like that?

this is a code example

import React from 'react'

let name: string

const ComponentA = () => {
 useEffect(() => {
  fetchName()
 }, [])

 const fechName = async () => {
  const _name = await backendService.getName()
  name = name
 }

 return (
  <>Anything</>
 )
}

console.log("name: ", name) // getting undefined


export default ComponentA