React-native maps; polygon wont render on my MapView and my function returns a completely different value than expected

export default function MapScreen() {
    return (
        <NavigationContainer independent={true}>
            <MapStack.Navigator initialRouteName="MapScreenView">
                <MapStack.Group screenOptions={{headerShown: false,}}>
                    <MapStack.Screen name="MapScreenView" component={MapScreenView} />
                </MapStack.Group>
            </MapStack.Navigator>
        </NavigationContainer>
    );
}; 

/*
MapScreenView

Primary ancestor component of the map screen functionality.
In charge of rendering the world map & polygons. 
*/
class MapScreenView extends React.Component {
    constructor () {
        super();
        this.mapHasMoved = false;
        this.currentRegion = 'Clemson';
        this.polysMap = [];
        this.polysReady = false;
        console.log("nnNew map loaded")
    }

    updateMapHasMoved = (val) => {
        console.log("before: mapHasMoved = " + this.mapHasMoved)
        this.mapHasMoved = val;
        console.log("after: mapHasMoved = " + this.mapHasMoved);
    }

    updatePolysReady = (val) => {
        this.polysReady = val;
        console.log("polysReady = ")
        console.log(val);
    }

    RenderPolygons = async (region = this.currentRegion) => {
        var polys = [];
    
        var response = '';
        var coords = [];
        try {
            response = await axios.get(`${baseURL}/ClemsonLots/`);
        } catch (error) {
            console.log("get error: " + error);
        }
        console.log("Rendering polygons for region: " + region)
        for (var i in response.data) {
            coords.push([i, response.data [i]]);
        }
    
        //Create array of objects storing parking lot poly information
        for (var i = 0; i<coords[0].length; i++) {
            polys[i] = 
                {lotID: coords[i][1].lotID,
                 numCoords: coords[i][1].numCoords,
                 lotCoords: []
                };
            };
        
        //Create variable sized objects of coordinate pairs
        //, store them in polys[i].lotCoords
        for (var i = 0; i<coords[0].length; i++) {
            if (coords[i][1].numCoords == 3) {
                /* if else block to assign coordinate values from database */}
        }
    
        
        polys.map((lot, index) => {
            this.polysMap[index] = <Polygon 
                key={lot.lotID}
                coordinates={lot.lotCoords}
                fillColor="#27f"
                strokeColor="#27f"
                strokeWidth={2}
                zIndex={2}
            />
            });
        //console.log(this.polysMap[0])
        return true;
    }

    render() {
        return (
            <View style={StylesList.appBackground}>
                <View style={styles.mapScreenContainer}>
                    <MapView style={styles.map} 
                    region={startingRegion} rotateEnabled={false}
                    showsBuildings={true}
                    onMapReady={() => this.updatePolysReady(this.RenderPolygons())}
                    >
                        {this.polysMap}
                        {this.polysReady ? console.log(this.polysReady) : null}
                        {/* { this.mapHasMoved ? this.RenderPolygons() : null} */}
                    </MapView>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    mapScreenContainer: {
        height: '85%',
        width: '100%',
        marginTop: 20,
        borderColor: '#000',
        borderWidth: 1,
    },
    map: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
});

const startingRegion = {
    latitude: 34.6738988,
    longitude: -82.8422494,
    latitudeDelta: 0.005,
    longitudeDelta: 0.001,
};

I’m making an app in React Native and I am trying to get it so that my map will render polygons based on coordinates in my database.

The problem I think lies in the RenderPolygons() function, but I’m new so Im not sure. The map itself loads when I run my code, but no polygons are loaded. I have tried logging the results to the console, and I can see and have tested by copying and pasting the values that the polysMap array correctly stores polygon blocks.

i.e. <MapPolygon coordinates={[{“latitude”: 34.6748, “longitude”: -82.8442}, {“latitude”: 34.6752, “longitude”: -82.8439}, {“latitude”: 34.6746, “longitude”: -82.8414}, {“latitude”: 34.6732, “longitude”: -82.8423}, {“latitude”: 34.674, “longitude”: -82.8434}]} fillColor=”#27f” strokeColor=”#27f” strokeWidth={2} zIndex={2} />

The above block is stored in polyMaps[0], and directly putting that in the render() function works. But calling {this.polyMaps} does not. When I tried running {console.log(this.polyMaps)} in the MapView, it just returns ‘[]’.

As a new attempt, I tried putting RenderPolygons() in another function and have it return true to update this.polysReady, but the console value of this.polysReady is “{“_h”: 0, “_i”: 0, “_j”: null, “_k”: null}”.

Apologies, I know there is a lot going on here but I am really stuck and any help is appreciated.

How to attach a file to file input using JavaScript in react native web view

I am building an application using react native which auto completes various Form Fields on third party websites by injecting a JavaScript Script send from the server for signed in user using injectedJavaScript method in react-native-webview package (https://github.com/react-native-webview/react-native-webview). I works for all the fields accept file fields. is there any way to do it. if not is there any other approach to auto complete file form fields on third party website. or any modifications we can make in react native webview to not block the requests to attach files

I have tried using injectedJavaScript method but it doesn’t work. I know due to browser security policies it is blocked. but we are using web view it there way to modify it

Updating addDomListener() to addEventListener() method

In a callback javascript file that supports a Google map (referenced by the html file) I have used the following Listener code responding to the click event on a checkbox:

window.eqfeed_callback = function (results) {
...
...
 google.maps.event.addDomListener(document.getElementById("cksites"), 'click', function () {
       ' turn on/off a layer on the map..
    });
...
...
};

When inspecting the page I am reminded that “addDomListerner” should be replaced by “addEventListener()” method since the latter is now deprecated (but will still work for the foreseeable future.).

“cksites” is the name of an checkbox that turns on/off a “layer” on the Google map.

A link to update this method is provided in the inspect view. I’ve tried numerous combinations of their suggestions and cannot seem to get an updated Listener in place. I was hoping to save some time as I am not by profession a Google map programmer.

One solution proposed adding: window.addEventListener(“load”, initMap); to solve the issue but does not say where in the code this line should be located (near the intiMap line ?)

Any help with this wuold be appreciated (the organization I work with has many of these click events so I thought it best to update them if I could).

Thanks in advance.

Check auth next.js in layout hoc or _app.js with getServerSideProps?

I usually checked accessToken in localStorage on the client, if it is there, then send a request from the client to reset tokens, but I want to give this task to the server, and therefore I put accessToken and refreshToken in cookies and try to send a request to the server with cookies.

How can I send a request to the server only 1 time when logging in to the application?

I want to check cookies on the server for the presence of refreshToken, and if they are there, then update the token and transfer the user’s data in the response (in the body)

I want to do this without an extra request from the client, that is, without using useEffect, but nothing comes out.

AppLayout.js

import Head from "next/head";

const AppLayout = ({ children, data }) => {
    console.log(data)// undefined
    return (
        <div className="layout">
            <Head>
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <header />
            <main>{children}</main>
            <footer />
        </div>
    );
};

export default AppLayout;

// why getServerSideProps dont work ?
export function getServerSideProps({ ctx }) {
    // console.log(ctx?.req?.headers?.cookie);
  
    const data = 'hello';
    console.log('getServerSideProps')// dont work
    return {
      data
    }
};

_app.js

import '@/styles/index.scss'
import AppLayout from '@/components/AppLayout/AppLayout'
import Link from 'next/link'

export default function App({ Component, pageProps }) {
  return (
    <AppLayout {...pageProps}>
      <Link href="/">home</Link>
      <Link href="gg">gg</Link>
      <Component {...pageProps} />
    </AppLayout>
  )
}

Comparing the Efficiency of CountingSort Implementations using Arrays vs Objects?

I have two implementation variation for countingSort algorithm.

#1 – Using an array to count the occurrences:

const countingSort1 = (arr) => {
  const max = Math.max(...arr);
  const count = new Array(max + 1).fill(0);
  for (let i = 0; i < arr.length; i++) {
    count[arr[i]]++;
  }

  console.log(count); // Array(120001) [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, …]

  let k = 0;
  for (let i = 0; i < count.length; i++) {
    for (let j = 0; j < count[i]; j++) {
      arr[k] = i;
      k++;
    }
  }
  return arr;
};

#2 – Using a dictionary (object) to count the occurrences:

const countingSort2 = (arr) => {
  const count = {};
  for (let i = 0; i < arr.length; i++) {
    const curr = arr[i];
    count[curr] = (count[curr] ?? 0) + 1;
  }

  console.log(count); // Object {3: 1, 5: 1, 24599: 1, 120000: 1}

  let i = 0;
  for (let val in count) {
    for (let j = 0; j < count[val]; j++) {
      arr[i] = +val;
      i++;
    }
  }
  return arr;
};

Usage:

const numbers = [3, 5, 24599, 120000];

console.log(countingSort1(numbers)); // [3, 5, 24599, 120000]
console.log(countingSort2(numbers)); // [3, 5, 24599, 120000]

Want to know:

When we have a wide range of numbers to sort with counting sort, the size of the counting array becomes very large, which can lead to memory issues.

This is correct because, as you can see, our range is from 3 to 120000, and the implementation shown in countingSort1() creates an array sized 120001 to accommodate all possible values. However, this is not the case in the second implementation, countingSort2().

So why do we talk about a ‘wide range’ (I know, more unique elements = more memory), and why is the countingSort1() style of implementation used more widely than countingSort2()? What are the drawbacks of using countingSort2()?

Socket.io Engine.io problems “?EIO=4&transport=polling&t=OUAHy-a 404”

When I try to connect the client to my website with socket.io, it just spams
https://example.com/socket.io/?EIO=4&transport=polling&t=OUAHy-a 404 (At other times the request has just timed out instead of 404) repeatedly in the client console.
Here is the client html:

<!DOCTYPE html>
<html>
  <head>
    <title>Zesty testy</title>
  </head>
  <body>
    <script src="https://cdn.socket.io/4.4.1/socket.io.js"></script>
    <script src="./client.js"></script>
  </body>
</html>

And here is the client js:

const socket = io();

At last, here is the server js:

var app = require('express')(); 
var server = require('http').Server(app); 
var io = require('socket.io')(server);

io.on('connection', (socket) => {
  console.log('a user connected');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

I have looked at many other questions alike mine, but no answer has been able to change the outcome.
Most of the code is from the socket.io webpage, with some slight change. I have been trying to get this to word for so long, and I will happily answer any questions to try and get this work. Thanks! (I am not using localhost.)

The expected result is for the Engine.io request thing to have status code 200 instead of 404, and the server console to display that a user has connected.

im getting an error “Invariant Violation: “main” has not been registered.”

Invariant Violation: “main” has not been registered. This can happen if:

  • Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
  • A module failed to load due to an error and AppRegistry.registerComponent wasn’t called., js engine: hermes
    at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:null in reportException
    at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:null in handleException
  • … 7 more stack frames from framework internals

enter image description here

I’m just calling one file . When I call that file it through thi error

why is my Node app returning 404 “file not found”

in my simple node app, my code keeps on return “404 file note found instead of my home page.
I have tried so many times to solve but isn’t working out yet.

const http = require('http');
const fs = require('fs');
const dir = './public/';
const port = process.env.PORT | 3000;

//creating the server and routing
// creating the server starts
const server = http.createServer( (req, res) =>{

    // routing the frontend here starts
    if(req.url === './') {
        render(res, 'index.html');
    }else if (req.url === '/about'){ 
        render(res, 'about.html');
    }else if (req.url === '/contact'){
        render(res, 'contact.html');
    }else{
        res.writeHead(404, {'Content-Type' : 'text/html'});
        res.end('<h1> 404 file not found </h1>');
    }
     // routing the frontend here end

}).listen(port, ()=>{
    console.log(`http://localhost:${port}`);
})
// creating the server endss sssssssssss

// we will load the document on the front end here (or we will use the fs read file here)
// startsssssssssssssss
const render = (res, file) => {
    fs.readFile(dir + file, (err, data) => {
        //if error
        if(err){
            res.writeHead(404, {'Content-Type' : 'text/html'});
        res.end('<h1> 404 file not found </h1>')
        }
        // if no error
        res.writeHead(200, {'Content-Type' : 'text/html'});
        res.write(data);
        res.end();
    });
}

I have tried using some other techniques but isn’t working out.

How can I set values to the ‘useState’ from the test file?

I am not sure how I can set values to the useState variables which are outside of the test file. I don’t have any props to the components as I am getting the data directly inside components using Axios.

export const AddTodo = () => {
  const [title, setTitle] = useState("");
  const [desc, setdesc] = useState(""); 
  const [error, seterror] = useState(false);
  const [descError, setdescError] = useState("");
  const [dbError, setdbError] = useState(false);

const submit = (e) => {
    e.preventDefault();

    title.length < 3 && seterror(true);
    desc.length < 5 && setdescError(true);

    console.log("Title and description", title, desc);
    if (!(title.length < 3 || desc.length < 5)) {
      setsrno(toDos[toDos.length - 1].srno + 1);
      const task = { title, desc };
      console.log("here is task", task);

      setTitle("");
      setdesc("");
      fetch("http://localhost:3031/todo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(task),
      })
        .then(() => {
          console.log("new task added");
        })
        .catch((err) => {
          return console.log(err), setdbError(true);
        });

    }
  };

return(<div className="container my-3">
      <form onSubmit={submit}>
        <div className="mb-3" data-testid="todo-title">
          <label htmlFor="title" className="form-label">
            Todo Title
          </label>
          <input
            type="text"
            value={title}
            onChange={(e) => {
              setTitle(e.target.value);
              titleValidation();
            }}
            className="form-control"
            id="titleId"
            aria-describedby="titleH"
          />
    
        </div>

        <div className="mb-3" data-testid="todo-desc">
          <label htmlFor="desc" className="form-label">
            Description
          </label>
          <input
            type="text"
            value={desc}
            onChange={(e) => {
              setdesc(e.target.value);
              descValidation();
            }}
            className="form-control"
            id="desc"
          />
  

        {dbError ? <DbErrorModal dbModal={true} /> : <div></div>}

     
          <button type="submit" className="btn btn-sm btn-success">
            Add Todo
          </button>
      </form>
);
};

  

How can I call setTitle() and setdesc() method?

  test("Should fire button", () => {
    const { getByRole } = render(<AddTodo />, { wrapper: BrowserRouter });
    const addTodoBtn = getByRole("button", { name: "Add Todo" });
    fireEvent.click(addTodoBtn);
  });

react-native-firebase Apple sign-in [Error: [auth/invalid-credential] The supplied auth credential is malformed or has expired.]

I have a react-native app using Firebase, useContext with the react-native-firebase package.

My useContext is as follows:

import React, {createContext, useState, FC, ReactNode} from 'react';
import auth, {FirebaseAuthTypes} from '@react-native-firebase/auth';
import appleAuth from '@invertase/react-native-apple-authentication';

type UserContextType = {
  user: FirebaseAuthTypes.User | null;
  signUp: (email: string, password: string) => Promise<void>;
  signIn: (email: string, password: string) => Promise<void>;
  signOut: () => Promise<void>;
  resetPassword: (email: string) => Promise<void>;
  signInWithApple: () => void;
};

export const UserContext = createContext<UserContextType>({
  user: null,
  signUp: async () => {},
  signIn: async () => {},
  signOut: async () => {},
  resetPassword: async () => {},
  signInWithApple: async () => {},
});

type Props = {
  children: ReactNode;
};

const UserProvider: FC<Props> = ({children}) => {
  const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);

  const signUp = async (email: string, password: string) => {
    try {
      const response = await auth().createUserWithEmailAndPassword(
        email,
        password,
      );
      setUser(response.user);
    } catch (error) {
      console.error(error);
    }
  };

  const signIn = async (email: string, password: string) => {
    try {
      const response = await auth().signInWithEmailAndPassword(email, password);
      setUser(response.user);
    } catch (error) {
      console.error(error);
    }
  };

  const signOut = async () => {
    try {
      await auth().signOut();
      setUser(null);
    } catch (error) {
      console.error(error);
    }
  };

  const resetPassword = async (email: string) => {
    try {
      await auth().sendPasswordResetEmail(email);
    } catch (error) {
      console.error(error);
    }
  };

  const signInWithApple = async () => {
    try {
      // Check if Sign in with Apple is supported
      const isSupported = await appleAuth.isSupported();
      if (!isSupported) {
        throw new Error('Sign in with Apple is not supported on this device');
      }

      // Start the sign-in request
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });

      // Ensure Apple returned a user identityToken
      if (!appleAuthRequestResponse.identityToken) {
        throw new Error('Apple Sign-In failed - no identity token returned');
      }

      // Create a Firebase credential from the response
      const {identityToken, nonce} = appleAuthRequestResponse;
      const appleCredential = auth.AppleAuthProvider.credential(
        identityToken,
        nonce,
      );

      // Sign the user in with the credential
      const authResult = await auth().signInWithCredential(appleCredential);
      const user = authResult.user;

      // Check if the user is new and update the display name
      if (authResult.additionalUserInfo?.isNewUser) {
        const fullName = appleAuthRequestResponse.fullName;
        if (fullName?.givenName && fullName?.familyName) {
          await user.updateProfile({
            displayName: `${fullName.givenName} ${fullName.familyName}`,
          });
        }
      }

      // Return the user object
      return user;
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <UserContext.Provider
      value={{user, signUp, signIn, signOut, resetPassword, signInWithApple}}>
      {children}
    </UserContext.Provider>
  );
};

export default UserProvider;

I have implemented it by calling the context:
const {signInWithApple} = useContext(UserContext);

and then using signInWithApple inside a touchableOpacity

I have enabled SignIn on Firebase:

Enable Firebase Apple sign in

I have also enabled the capabilities within XCode:

Xcode

However, after following all of the implementation steps. I still receive the error:
ERROR [Error: [auth/invalid-credential] The supplied auth credential is malformed or has expired.]

I thought that this might be because I was testing on a simulator? But I got my real device up and running and it seemed to be the same issue.
I also saw online that you have to fill in the service ID, but it looks like that should just be for Android.

Any help is appreciated. Thank you!

ReactJS app not immediately running when mobile browser visits website, and takes 3 seconds for the code to start running

I am using ReactJS. When I visit the website using my phone, it seems to display instantly (maybe a cached version?) and only after 3 seconds does the website actually begin to run the javascript code that pulls data from a database.

Is there a way to prevent this latency? I.e. once user visits reactjs website, it should immediately start running the javascript.

I suspect it might be a caching issue, as the website seems to load instantly when I hit enter on my phone, and it takes some time to actually download the index.js and all from my webserver. But at the same time I’m not sure, is there a way to test this too?

Thanks, and cheers for the help.

Distance approximation between two pincodes

I am developing a React application which is essentially a Truck Rental system. I have a set of pair of two pincodes with me: one is the source and other of destination. I want to calculate the distance between these two pincodes (approximate) and compare them with all possible combinations. How do I calculate this approximate distance between two pincodes in a React application?

I could not find any free API supporting the same requirement. I looked at a couple of API’s like Google Maps API( Distance Matrix one is paid), OpenStreetMap, etc.
Any help would be greatly appreciated.