I am passing the state to a functional component via history (react-router-dom) but it says the state is ‘undefined’ [duplicate]

I need to pass the state value to a different component and I want to use it in the different component.

Code in the first component:

    const handleFormSubmit = async (event) => {
        event.preventDefault()
        console.log(formData)
        try {
            await axios
                .post(`http://localhost:4000/accounts/register`, formData)
                .then(function (response) {
                    console.log(response)
                    console.log(response.data)
                    setServerMessage(response.data)
                })
        } catch (error) {
            console.log(error)
        }
        history({
            pathname: '/session/verifyotp',
            state: { serverMessage: serverMessage.message },
        })
    }

The second component where I am trying to access the state.

    const navigate = useNavigate()
    let data = useLocation()
    console.log(data)

The output I am getting in the browser console is:

Object { pathname: "/session/verifyotp", search: "", hash: "", state: null, key: "n1jhatdj" }

how can I access the state value? why is it coming as null? Thanks in advance for your help.

The speak function should work each time a question comes on screen, but it does not work for very first question and works fine after that

I have made a component using react-speech-kit, it should speak the question whenever it comes on screen, but the speak function does not work fr the very first question and works fine after that

import { useSpeechSynthesis } from 'react-speech-kit';
import { useEffect } from 'react';

const TextToSpeech = ({question}) => {
  const {speak} = useSpeechSynthesis();

  useEffect(() => {
    speak({text:question});
  }, [question]);

}

export default TextToSpeech;

Same nextPageUrl in flipkart API pagination

let axios = require('axios')

let getShipmentDetails = async (url) => {

        var res = await axios({
            method: 'post',
            url: url,
            headers: { Authorization: "<Bearer token>"},
            data: {
                "filter" : {
                    "type" : "postDispatch",
                    "states" : ["Delivered"],
                    "orderDate" : {
                        "from" : "2022-03-02",
                        "to" : "2022-03-10"
                    }
                }
            }
        })

        if (res['data']['hasMore'] == true) {
            var newurl = "https://api.flipkart.net/sellers"+res['data']['nextPageUrl'];
            console.log(newurl)
            let more = await getShipmentDetails(newurl)
            return res['data']['shipments'].concat(more);
        }
        else {
            console.log(res['data'])
            return res['data']['shipments']
        }
}

getShipmentDetails("https://api.flipkart.net/sellers/v3/shipments/filter/")
.then(result => {})

The newUrl is same everytime. I cannot able to access content of next page in results.

Documentation

res[‘data’][‘nextPageUrl’] =
/v3/shipments/filter?next_token=ewogICJmaWx0ZXJUeXBlIiA6ICJwb3N0RGlzcG……GF0ZSIgOiAib2FwaV9wb3N0X2Rpc3BhdGNoIgp9

i have used chrome.storage.sync.set to init data when my extensions install,but i cannot read them in background,js [duplicate]

chrome.runtime.onInstalled.addListener{
let urlobj={}
chrome.storage.sync.set(urlobj}

chrome.alarms.create("everyDay",{when:Date.now(),periodInMinutes:1})
chrome.alarms.onAlarm.addListener((alarm)=>{
        chrome.storage.sync.get(urlobj,(data)=>{
            console.log("is reading urlobj"+data)
        })
)

I run on chrome,the devtool say that Error in event handler: ReferenceError: urlobj is not definederro at chrome.storage.sync.get(urlobj).How can read the storage?And why i cannot see storage in devtool?

Dynamic Icon Component breaks Jest test (in NextJS/React)

So very new to the community, because I usually find the answer to my questions just by searching the community. But this one I can’t figure out.

My Setup

I am using NextJS just as a framework application, so I don’t use any of its API abilities. So far no tests implemented, but now I got more time on my hands. I want to implement tests using Jest and later on implementing some e2e such as playwright. But for now Jest.

The Problem

So I am implementing Jest in my application, but somehow cannot run the test because I am using a Dynamic Icon Component within my application.

So what is this icon component I am talking about. I got tired of importing icons one by one in each page. So decided to create one component that has the name attribute, so I can pass it any SVG name and it would just render it on my screen.

// Icon.jsx

import Company from './icons/company.svg';

const iconTypes = {
  'company': Company,
}

const Icon = ({ name, ...props }) => {
  let Icon = iconTypes[name];
  return <Icon {...props} />;
};

export default Icon;
// next.config.json

module.exports = {
  webpack(config) {
    config.resolve.fallback = { fs: false };
    config.module.rules.push({
      test: /.svg$/,
      use: ["@svgr/webpack"]
    });
    return config;
  },
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
  reactStrictMode: true,
}

So this pretty much allows me to import an Icon by simply saying on anypage:

<Icon name="company" />

Now when implementing Jest, this component causes a lot of troubles with running my tests. I get the following error, when running my test:

    Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
    
    Check your code at Icon.jsx:119.

...

      117 |   console.log(1111111, name)
      118 |   let Icon = iconTypes[name];
    > 119 |   return <Icon {...props} />;
          |          ^
      120 | };
      121 |
      122 | export default Icon;

      at printWarning (node_modules/react/cjs/react.development.js:220:30)
      at error (node_modules/react/cjs/react.development.js:196:5)
      at createElementWithValidation (node_modules/react/cjs/react.development.js:2215:7)
      at Icon (res/images/Icon.jsx:119:10)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
      at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:17811:13)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:19049:16)

So this error message I usually get when I pass in a name of an icon that does not exist.

So at this point I’m a bit confused on how to handle this? Is there a way to ignore this component when running the test? Or run it somehow.

Some things I already tried

//jest.config.js

module.exports = {
  "transform": {
    "^.+\.jsx?$": "babel-jest",
    "^.+\.svg$": "<rootDir>/svgTransform.js"
  },
  setupFilesAfterEnv: ["./jest.setup.js"],
  moduleNameMapper: {
    "^@/libs(.*)$": "<rootDir>/libs$1",
    "^@/res(.*)$": "<rootDir>/res$1",
    "^@/store(.*)$": "<rootDir>/store$1",
    "^@/pages(.*)$": "<rootDir>/pages$1",
    '^.+\.(css|less|scss)$': '<rootDir>/styleMock.js'
  },
};
// svgTransform.js

module.exports = {
  process() {
    return 'module.exports = {};';
  },
  getCacheKey() {
    // The output is always the same.
    return 'svgTransform';
  },
};

How can I do generic function with return TypedEmitter

I want to make a tiny system that hold emitter for specific interface like this.

I am using https://github.com/binier/tiny-typed-emitter

Please help me what I am do wrong. Thanks you alot.

interface IEvenListener
{
}

interface IPlayerJoinedListener extends IEvenListener
{
    onPlayerJoined: (playerId: string) => void;
}

let emitter: TypedEmitter = ...;

function getEmitter<T extends IEvenListener>(): TypedEmitter<T> // error here
{
    return emitter as TypedEmitter<T>;
}

const messageEmitter = getEmitter<IPlayerJoinedListener>();

But it print out error

Type 'T' does not satisfy the constraint 'ListenerSignature<T>'.
Type 'IEvenListener' is not assignable to type 'ListenerSignature<T>'.ts(2344)

React App running fine on localhost but not able to fetch static files like main.chunk.js, bundle.js and 0.chunk.js etc

The Application is running fine on localhost but when the react app development server is hosted on production with a public Ip and accessed using that public Ip the page is not able to fetch static files like favicon, main.chunk.js, bundle.js, and 0.chunk.js, etc. I am proxying react app development server with Nginx using a route /rx on this production server. I had begun this project using create-react-app. It was working fine till now but suddenly this problem has popped up and even reverting the commits to earlier stable ones is not helping.

My index.js looks like this

enter image description here

This is how my package.json looks like

enter image description here

This is how my app.js looks

enter image description here

Here are the error Screen Shots when accessed over public ip

enter image description here

However everything is working fine when same code is accessed over localhost as seen follows.

enter image description here

How to test api with dummy data within code in React native?

I am creating a SignUp Page for which used fetch to get data from an api. For which I want to test it with dummy data within the code itself.

const Signup: FC<AuthNavigationProps<'Signup'>> = () => {
  const {control, handleSubmit} = useForm();
  const {setUser} = useUser();
  const toast = useToast();

  const signup: SubmitHandler<ISignupValues> = async ({email, password}) => {
    try {
      const res = await fetch(`${config.apiUrl}/api/signup`, {
        method: 'POST',
        body: JSON.stringify({
          email,
          password,
        }),
      });
      if (res.ok) {
        await setGenericPassword(email, password, CREDENTIALS_STORAGE_OPTIONS);
        setUser({isLoggedIn: true, hasSessionExpired: false});
        toast.setToast({message: 'Signup has succeeded', visible: true});
      }
    } catch (error) {
      toast.setToast({message: 'Signup failed', visible: true});
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.helloText}>Welcome Tayze User!</Text>
      <TextInput
        placeholder="Email"
        // inputProps={{keyboardType: 'email-address', autoCorrect: false}}
        autoCorrect
        style={styles.textInput}
      />
      <TextInput
        placeholder="Password"
        // inputProps={{secureTextEntry: true}}
        secureTextEntry
        style={styles.textInput}
      />
      <Button label="Sign up" onPress={() => handleSubmit(signup)()} />
    </View>
  );
};

export default Signup;

I want to create one mock data here and call it to check the login and signup pages.

Javascript click action not triggering of input date

I am trying to trigger the opening of a calendar date picker when clicking on a related text field. My HTML looks like this:

<form action="test.html" method="post">
   <input type="date" id="dueDate" name="dueDate">
   <input type="text" id="dateText" name="dateText" onclick="dateTextClick()">
</form>

and my Javascript looks like this:

<script>
    function dateTextClick() {
        var $input = document.querySelector("#dueDate");
        $input.focus();
        $input.click();
    }
</script>

The first line does work, and the date input receives the focus. However, the click action is not triggered, so the date picker calendar does not appear.

In case it’s relevant, this code is embedded in a Joomla article, but so far in my experience that hasn’t made a difference to the use ofJavascript.

I would be grateful for any pointers as to how to fix this!

How to customize the @react-navigation/material-top-tabs

I’m using @react-navigation/material-top-tabs and I need to customize the default style. expected image

code ,

<Tab.Navigator
        style={{ marginTop: 100 }}
        tabBarOptions={{
          activeTintColor: '#FFFFFF',
          labelStyle: {
            textTransform: 'none',
          },
          inactiveTintColor: '#FFFFFF',
          indicatorStyle: {
            height: 30,
            top: '10%',
            bottom: '10%',
            width: '45%',
            left: '2.5%',
            borderRadius: 10,
            backgroundColor: '#0099CC',
          },
          style: {
            alignSelf: 'center',
            width: '70%',
            borderRadius: 10,
            borderColor: 'blue',
            backgroundColor: '#434343',
            elevation: 5, // shadow on Android
            shadowOpacity: 0.1, // shadow on iOS,
            shadowRadius: 4, // shadow blur on iOS
          },
          tabStyle: {
            borderRadius: 10,
          },
        }}
        swipeEnabled={true}>

How to convert this to react navigation 6 and how to add this as custom component.
Note : I was using react navigation 6

html diable text box when radio button is selected

I am trying to write javascript to disable textbox if radio benter code hereutton is selected. I have 4 options for radio button and corresponding textbox. even if I am selecting radio button 2 I am able to write values in radio 1 text and submit. So want to add method on click or on change of radio button selection option. I have below javascript function but its not being called on event. Am I doing anything wrong, why javascript is not being called? any help would be appreciated. I am new to javascripts.
enter image description here

{% extends "layout.html" %}
{% block body %}
<html>
<head>

    <meta charset="UTF-8">
    
               <script type="text/javascript">
    
        function EnableDisableTextBox() {
            alert("good")
            var chkYes = document.getElementById("search1");
            alert("Today's date is " chkYes);
            var text1 = document.getElementById("text1");
            alert('java script')
            text1.disabled = chkYes.checked ? false : true;
            if (!text1.disabled) {
                text1.focus();
            }
        }
    </script>
    <form method="post">
        <br><br><br>
        <input type="radio"   onchange="EnableDisableTextBox()"   align="center" name="search" id="search1" value="" > By Keyword <input type="text" id="text1" name="text1" for="search1"></input> <br>
        <input type="radio" align="center" name="search" id="search2" value="" id="search2" > In PostalCode <input type="text"  name="text2" id="text2" for="search2"></input><br>
        <input type="radio" align="center" name="search" id="search3" value="" id="search3" >Within<input type="number" name="text3" id="text3" for="search3" step="1" max="150" min="0">miles of me</input><br>
        <input type="radio" align="center" name="search" id="search4" value="Search4" id="search4" >In My PostalCode<br><br><br>
        <button name="button"  id="btn" onclick="window.location.href='/search/{{search}}'">Search</button>
    
           </form>
    
        </head>
    
    
    </html>
    
    {% endblock %}

Anylogic Error Source Arrival Table in DB based Variable (Not Unique Database Value!)

I have combo box in experiment screen with options : Lala, Poo, and Twinky. They will be input in variable as initial value. Lala, Poo, and Twinky. Also their database for arrival table :

enter image description here

I am trying to make source based on variable as below :

enter image description here

but I get this problem :

enter image description here

My objective is if I choose Lala, then Lala database arrival date will be used.
Hope you can help me, thanks

Javascript – Adding new element to array using for loop

I’m trying to convert url. Using for loop to extract Acura, Audi. Here what I got so far:

var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';

const newSrpParamsArray = newSrpParams.split("&");

var oldSrpParams;

var makes = [];

for(var i = 0 ; i < newSrpParamsArray.length; i++){
  if(newSrpParamsArray[i].includes('make')) {
    const make = newSrpParamsArray[i].replace('make=','')
    makes.push(make);
    console.log(makes)
  }
};

The result is

[ 'Acura' ]
[ 'Acura', 'Audi' ]

As you see it has one more array. Is there a way to get only [ 'Acura', 'Audi' ]?

How can I fix this code to get all prime numbers within a range?

So I am testing my algorithm and trying to print all prime numbers within a range. I think the code is logical but it keeps printing the wrong output i.e the unfiltered list of numbers.

function sumPrimes(num) {
  // Check all numbers for primality
  let a = []
  let b = []
  for (let i = 2; i <= num; i++) {
      a.push(i)
      b.push(i)
  }
  //console.log(a)
  return a.filter(function(item) {
    for(let j = 0; j < b.length; j++) {
      if(item !== b[j] && item % b[j] != 0) {
        return true
      } 
    }
    return false; 
  })
}
sumPrimes(977);