Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all 6288 articles
Browse latest View live

Module '"./node_modules/react-native"' has no exported member 'View'

$
0
0

After i convert my project in typescript showing me following errorModule '"./node_modules/react-native"' has no exported member 'View'.

import React from 'react';import {StyleSheet,View,Text} from 'react-native';export default function App() {return (<View style={{ flex: 1 }}><Text>Welcome</Text></View> );}

React navigation name issue

$
0
0

Ive inherited some code here and I'm just confused as to how the app knows where the 'NextPage' is.

I call this:

            this.props.navigation.navigate('NextPage');

With this:

import { NavigationScreenProp } from 'react-navigation';interface InitialLoadingScreenViewProps {    navigation: NavigationScreenProp<any, any>}

where is the 'NextPage' declared? so that when I create a new page I can create a navigation name for it. Ive tried using the search tool on VSCode but couldn't find it.

Poll and update state UNLESS a specific prop updates

$
0
0

I'm building a React Native application that is polling for wallet balances every 6 seconds. I've setup a timer which I am using to 1) call ONCE initially for balance (ie. not wait 6 seconds for the interval in my timer to run) and 2) poll as normal after that.

The problem I'm having is the user can change the state while the polling is happening but because the interval is already running what happens is the user updates the state then the polling code overwrites it.

For example given assetBalances of:

{ lorem: { balance: 100 } }

If the user were to change the wallet name from "lorem" to "ipsum" I'd momentarily be left with assetBalances of:

{ ipsum: { balance: 100 } }

Which would then quickly become the following when the poll has ran. (The reason it adds to the object is because I spread with ... as you can see in network-scan.ts):

{ lorem: { balance: 100 }, ipsum: { balance: 100 } }

I've tried using a custom usePrevious hook which compares the last prop to current prop and then I conditionally call the setAsyncValue in network-scan.ts but that didn't work.

I need a way to CANCEL the running timer.start instance if x prop changes (x being assetBalances in my first case).

On a side note I'm also having an issue where for some reason when there's lots of state changes the timer gets called multiple times which causes loads of intervals to run parallelly, which I don't understand because I'm calling timer.stop() at the start of every useEffect re-render - why?

If anyone has any ideas as to how I can solve these issues I'd really appreciate it! Or is there a much easier way to do what I'm trying to do? Here's some code for context:

timer.ts

const timer = {  running: false,  timeout: false,  cb: function () {},  start: function (cb: any, iv: number, cbAtEnd?: any) {    const elm = this;    clearInterval(this.timeout);    this.running = true;    if (cb) this.cb = cb;    this.timeout = setTimeout(function () {      elm.execute(elm);      if (cbAtEnd) cbAtEnd();    }, iv);  },  execute: function (e: any) {    if (!e.running) return false;    e.cb();    e.start();  },  stop: function () {    this.running = false;  },};

polling.ts

export default function useNetworkPolling(): void {  const {    state: {      wallets,      userToken,      assetBalances,      selectedWallet,      connectedNetwork,      networkPollingInterval,      networkSpecificTokens,    },    setAsyncValue,  } = useContext(LocalContext);  const intervalTime = networkPollingInterval // default 6s  const address = useGetWalletAddress(selectedWallet);  useEffect(() => {    function scan() {      console.log(`Scan now! - (Interval time is: ${intervalTime}ms) [from useNetworkPolling]`);      const filteredTokens = getTokensFilteredByTrackedStatus(        connectedNetwork,        networkSpecificTokens      );      const allTokens = CORE_TOKENS.concat(filteredTokens);      handleNetworkScan(        allTokens,        JSON.parse(assetBalances),        address,        setAsyncValue,        connectedNetwork,        selectedWallet      );      console.log(JSON.stringify(JSON.parse(assetBalances), null, 2));    }    timer.stop(); // Make sure the previous one is stopped so two never run at the same time    if (userToken && JSON.parse(wallets).length) {      // Start off with an immediate one-off call      timer.start(scan, 1, () => {        timer.stop(); // Pass a callback into the start function which stops the first timer        timer.start(scan, intervalTime); // Start polling with the interval      });    }  }, [    address,    userToken,    networkPollingInterval,    wallets,    connectedNetwork,    networkSpecificTokens,    assetBalances,    selectedWallet,  ]);}

network-scan.ts

export default async function handleNetworkScan(  coreAndTrackedTokens: Token[],  assetBalances: any,  address: string,  setAsyncValue: (key: string, value: string) => Promise<void>,  connectedNetwork: string,  selectedWallet: string) {  let updatedBalances = assetBalances[selectedWallet];  for (const token of coreAndTrackedTokens) {    try {      // Redacted logic that updates updatedBalances if success...    } catch (e) {      // Redacted logic that updates updatedBalances if error...    }  }  setAsyncValue('assetBalances',    JSON.stringify({ ...assetBalances, [selectedWallet]: updatedBalances })  );}

How to mock React Navigation's navigation prop for unit tests with TypeScript in React Native?

$
0
0

I'm building a React Native app with TypeScript. For my navigation I use React Navigation and for my unit testing I use Jest and Enzyme.

Here is the (stripped down) code for one of my screen (LoadingScreen.tsx):

import styles from "./styles";import React, { Component } from "react";import { Text, View } from "react-native";import { NavigationScreenProps } from "react-navigation";// Is this correct?export class LoadingScreen extends Component<NavigationScreenProps> {// Or should I've done:// export interface Props {//   navigation: NavigationScreenProp<any, any>;// }// export class LoadingScreen extends Component<Props> {  componentDidMount = () => {    this.props.navigation.navigate("LoginScreen");  };  render() {    return (<View style={styles.container}><Text>This is the LoadingScreen.</Text></View>    );  }}export default LoadingScreen;

When trying to test the screens I came across a problem. The screens expects a prop with a type of NavigiationScreenProps because I'm accessing React Navigations navigation prop. Here is the testing file's code (LoadingScreen.test.tsx):

import { LoadingScreen } from "./LoadingScreen";import { shallow, ShallowWrapper } from "enzyme";import React from "react";import { View } from "react-native";import * as navigation from "react-navigation";const createTestProps = (props: Object) => ({  ...props});describe("LoadingScreen", () => {  describe("rendering", () => {    let wrapper: ShallowWrapper;    let props: Object;    beforeEach(() => {      props = createTestProps({});      wrapper = shallow(<LoadingScreen {...props} />);    });    it("should render a <View />", () => {      expect(wrapper.find(View)).toHaveLength(1);    });  });});

The problem is, that LoadingScreen expects a navigation prop.

I get the error:

[ts]Type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }' is not assignable to type 'Readonly<NavigationScreenProps<NavigationParams, any>>'.  Property 'navigation' is missing in type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }'.(alias) class LoadingScreen

How can I fix this?

I think I somehow have to mock the navigation prop. I tried doing that (as you can see I imported * from React Navigation in my test), but couldn't figure out. There is only NavigationActions that is remotely useful but it only includes navigate(). TypeScript expects everything, even the state, to be mocked. How can I mock the navigation prop?

Edit 1: Is the approach of using NavigationScreenProps even correct or should I use the interface Props approach? If yes how would you then mock than (it results in the same error).

Edit 2:Using the second approach with the interface and

export class LoadingScreen extends Component<Props, object>

I was able to "solve" this problem. I literally had to mock every single property of the navigation object like this:

const createTestProps = (props: Object) => ({  navigation: {    state: { params: {} },    dispatch: jest.fn(),    goBack: jest.fn(),    dismiss: jest.fn(),    navigate: jest.fn(),    openDrawer: jest.fn(),    closeDrawer: jest.fn(),    toggleDrawer: jest.fn(),    getParam: jest.fn(),    setParams: jest.fn(),    addListener: jest.fn(),    push: jest.fn(),    replace: jest.fn(),    pop: jest.fn(),    popToTop: jest.fn(),    isFocused: jest.fn()  },  ...props});

The question remains: Is this correct? Or is there a better solution?

Edit 3:Back when I used JS, it was enough to mock only the property I needed (often just navigate). But since I started using TypeScript, I had to mock every single aspects of navigation. Otherwise TypeScript would complain that the component expects a prop with a different type.

How to fix "TypeError: Cannot read property 'text' of null" for typescript react expo

$
0
0

I am getting this error whenever I try to set the value of my TextInput to a state of the code, here is the code for that:

<TextInput style={styles.inputBox} placeholder="Word Here" onChangeText={text2 => {  this.setState({   text: text2  }); }} value={this.state.text}/>

here is my entire files code just in case:

import React, { Component } from 'react';import {  StyleSheet,  Text,  View,  TextInput,  TouchableOpacity,} from 'react-native';import { Header } from 'react-native-elements';import { SafeAreaProvider } from 'react-native-safe-area-context';type prop = {};type state = {  text: string,  displayText: string,  word: string,  lexCategory: string,  def: string,  isSearched: boolean,  examples: Array<[]>}export default class App extends Component<prop, state> {  getText = (word: string) => {    var searchKeyWord = word.toLowerCase();    var url = "https://rupinwhitehatjr.github.io/dictionary/" + searchKeyWord +".json"    return fetch(url).then(data => {      if (data.status === 200) {        return data.json();      } else {        return null;      }    }).then(response => {      var responseObj = response      console.log(responseObj)      if (responseObj) {        this.setState({          word: this.state.text.toLowerCase(),          lexCategory: responseObj["definitions"][0]["wordtype"],          def: responseObj["definitions"][0]["description"],          isSearched: false        });      } else {        this.setState({          word: this.state.text.toLowerCase(),          lexCategory: "Word not found",          def: "Word not found",          isSearched: false        });      }    });  }  render() {    return (<SafeAreaProvider><View><Header            backgroundColor={'#81007e'}            centerComponent={{              text: 'Pocket Dictionary',              style: { color: '#fff', fontSize: 20 },            }}          /><TextInput            style={styles.inputBox}            placeholder="Word Here"            onChangeText={text2 => {              this.setState({                text: text2              });            }}            value={this.state.text}          /><TouchableOpacity style={styles.searchButton} onPress={() => {            this.getText(this.state.text)            this.setState({              displayText: this.state.text,              isSearched: true            });          }}><Text style={styles.searchText}>Search</Text></TouchableOpacity><Text style={styles.words}>Word:</Text><Text style={styles.wordResult}>{this.state.displayText}</Text><Text style={styles.words}>Type:</Text><Text style={styles.wordResult}>{this.state.lexCategory}</Text><Text style={styles.words}>Definition:</Text><Text style={styles.wordResult}>{this.state.def}</Text></View></SafeAreaProvider>    );  }}const styles = StyleSheet.create({  inputBox: {    marginTop: 100,    width: '80%',    alignSelf: 'center',    height: 40,    textAlign: 'center',    borderWidth: 4,    outline: 'none',  },  searchButton: {    width: '25%',    height: 55,    alignSelf: 'center',    margin: 20,    borderWidth: 5,    borderRadius: 20,  },  searchText: {    textAlign: 'center',    fontSize: 30,    fontWeight: 'bold',  },  words: {    textAlign: 'center',    color: 'gold',    fontSize: 20,    fontWeight: 'bold',  },  wordResult: {    fontSize: 20,    fontWeight: 'bold',    textAlign: 'center',  },});

Image of the error on the web page:Error

How to pass data back to previous screen in react native navigation v5?

$
0
0

I just updated to react native navigation version 5. Now I am trying to send data back to previous screen on goBack() call.

I push next view with

const onSelectCountry = item => {    console.log(item);};navigation.navigate('SelectionScreen', {        onSelect: onSelectCountry});

And making move back after selecting item from FlatList with call:

function onSelectedItem(item) {    route.params.onSelect(item);    navigation.goBack();}

But by sending function over with params I get a warning: Non-serializable valuse were found in the navigation state...

Can someone please tell me correct way to do this.

How do you write JavaScript within HTML of TypeScript file?

$
0
0

I am developing a project with React Native which uses TypeScript. And coming from React.js, I noticed I am not able to put JavaScript within the HTML. Is there a way I can use the following code within .jsx HTML?

import * as React from 'react';import { StyleSheet, TextInput } from 'react-native';import { Text, View } from '../components/Themed';export default function SearchScreen() {  const [searchText, setSearchText] = React.useState('');  const [searchData, setSearchData] = React.useState([]);  React.useEffect(() => {    if (searchText !== "") {      fetch(`https://morning-star.p.rapidapi.com/market/v2/auto-complete?q=${searchText}`, {"method": "GET","headers": {"x-rapidapi-key": "sensitivedata","x-rapidapi-host": "morning-star.p.rapidapi.com"        }      })      .then(function(response) {        return response.json();      }).then(function(data) {        console.log(data.results);        setSearchData(data.results);      });    }  }, [searchText]);  return (<View style={styles.container}><TextInput      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}      onChangeText={text => setSearchText(text)}      value={searchText}    />  {    searchData.map((stock, index) => (<Text key={index}>{stock.symbol}</Text>    )  }</View>  );}

I am basically attempting to display data from an API, save it in a state, and display it by mapping it. Is there a specific way you are supposed to display data/map it from within this component?

How do I configure absolute paths for imports in TypeScript based React Native apps?

$
0
0

In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.

It is important that the configuration also supports Jest unit tests.

I created the app using npx react-native init MyTestApp --template typescript

React Native version: 0.60.5

What is the exact configuration I would need to achieve this?


Import types two different project

$
0
0

I have a project which includes two sub projects. Web for web(react), native for RN. I have common styles for components, then I created interfaces. Developer could write web or native style codes. The following interface has buttonStyle. buttonStyle React.CSSProperties type for Web, ViewStyle type for RN. My issue is I cannot import these interface from common interface. I have to import these interfaces two project. It causes code duplicate. How can I import these interfaces from common file.

Project structure

common interface for button

Css Properties and TextStyle Types

$
0
0

I have a textStyle which is a type of TextStyle (it comes from react-native types) or React.CSSProperties. I want to pass this type to style attribute for html span element. style attribute accepts type of React.CSSProperties. My interface and span element is:

export interface IBaseTextStyleType {    textStyle:  React.CSSProperties | TextStyle}<span style={style.textStyle}>    {this.props.children || this.props.text}</span>

I got this error in style of span:

Type 'CSSProperties | TextStyle' is not assignable to type 'CSSProperties'.  Type 'TextStyle' is not assignable to type 'CSSProperties'.    Types of property 'aspectRatio' are incompatible.      Type 'number' is not assignable to type 'AspectRatio'.

How can I rid of this error ?

How to set autocomplete for react native elements input on iOS?

$
0
0

I am trying to set correct autocomplete suggestions on my registration form.I am using react native elements input, I have set username, email and password field.On email field I have set

textContentType={'emailAddress'}keyboardType={'email-address'}autoCompleteType={'email'}

and even so the keyboard is offering me only passwords for autocomplete.But even weirder is that if I add another input the email autocomplete works fine.Does anyone know is there anything I should be focusing on?

Unknown Option error from Babel in React-Native app

$
0
0

I ma building a react-native app with typescript in order to learn react native. Once I run the app with expo start and try to run on emulator I get this error:

index.js: [BABEL] ......../index.js: Unknown option: .name. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options

Actually I didn't have this error before. I tried to install react-native-dotenv package and while doing it installed metro-react-native-babel-preset too, which I am not sure whether was already installed or not.

My package.json is as follows:

{"name": "mobile-app","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint . --ext .js,.jsx,.ts,.tsx" },"dependencies": {"@react-native-community/async-storage": "^1.12.0","@react-native-community/google-signin": "^4.0.3","@types/axios": "^0.14.0","axios": "^0.20.0","expo": "^38.0.10","react": "16.13.1","react-native": "0.62.2" },"devDependencies": {"@babel/core": "^7.8.4","@babel/runtime": "^7.8.4","@react-native-community/eslint-config": "^1.1.0","@types/jest": "^25.2.3","@types/react-native": "^0.63.2","@types/react-native-dotenv": "^0.2.0","@types/react-test-renderer": "^16.9.2","@typescript-eslint/eslint-plugin": "^2.27.0","@typescript-eslint/parser": "^2.27.0","babel-jest": "^25.1.0","eslint": "^6.5.1","jest": "^25.1.0","react-native-clean-project": "^3.4.0","react-native-dotenv": "^2.4.1","react-test-renderer": "16.13.1","typescript": "^3.8.3" },"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json","node"   ] }}

babel.config.js :

module.exports = {  presets: ['module:metro-react-native-babel-preset', 'module:react-native-dotenv'],};

index.js

/** * @format */import { AppRegistry } from 'react-native';import App from './App';import { name as appName } from './app.json';AppRegistry.registerComponent('main', () => App);

React Native Typescript Formik cast event type

$
0
0

In the Formik documentation for React Native it has an example form:

<Formik initialValues={{ email: '' }} onSubmit={(values) => console.log(values)}>  {({ handleChange, handleBlur, handleSubmit, values }) => (<View><TextInput onChangeText={handleChange('email')} onBlur={handleBlur('email')} value={values.email} /><Button onPress={handleSubmit} title="Submit" /></View>  )}</Formik>

This, however, gives me a Typescript error:

No overload matches this call.Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.  Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.    Types of parameters 'e' and 'ev' are incompatible.      Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.

Given that I am getting the handleSubmit function from destructuring, how can I cast the type of event correctly?

Note: I know I can do this, but I have read that this will cause additional renders in React:

<Button onPress={(e) => handleSubmit(e as any)} title="Submit" />

Why does consulting a json file take so long on the real device and on the emulator is immediate?

$
0
0

I execute a query to a json file through the fetch function and in the emulator the result is immediate, it takes a century on the real device (motorola one vision) to give results.

What can it be? I isolated the code in a project from scratch to see and the problem really is in the type of query.

Could it be some gradlew configuration when generating the APK?

Thank you in advance!

import React, { useState } from 'react';import {    View,    Text,    ActivityIndicator} from 'react-native';export default () => {          const [status, setStatus] = useState(false);    fetch('https://senhor.app/trilhas/restaurantes.json').then(data => setStatus(true));    return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Funcional</Text>            {                status                ?   <Text>Carregou</Text>                : <ActivityIndicator size="large" color="#00ff00" />            }</View>    );}

Component Exception: Too many re-renders

$
0
0

I' ve go a problem with passing data between screens.Here is the screen where i'm taking input:

import React, {useState} from 'react'import {View, TextInput, Button, StyleSheet, TouchableWithoutFeedback, Keyboard} from 'react-native'import Card from '../components/Card'import colors from '../constants/colors';type Props={navigation:any}const AddingScreen = (props:Props) =>{    let annmountAndProductToSend:any;    const [enteredProduct, setEnteredProduct] = useState<string>('');    const [ammount, setAmmount] = useState<any>('');    function enteredProductHandler(enteredText:string):void    {        setEnteredProduct(enteredText);    }    function ammountHandler(enteredText:any):void    {        let ammountAndProduct;        const amm = parseInt(enteredText);        if(isNaN(enteredText) || enteredText > 1)        {            setAmmount(enteredText);            ammountAndProduct = enteredText +''+ enteredProduct;            annmountAndProductToSend = ammountAndProduct;        }        else setAmmount('')    }    function confirmProduct()    {        props.navigation.navigate('Main',{input:enteredProduct});        setEnteredProduct('');        setAmmount('');    }    function returnToMainScreen()    {        props.navigation.navigate('Main')    }    return(<TouchableWithoutFeedback onPress = {() => {Keyboard.dismiss();}}><View style = {styles.inputContainer}><Card style = {styles.screen} ><TextInput blurOnSubmit autoCapitalize="none"                    placeholder="Nazwa przedmiotu"                     style={styles.input}                     onChangeText={enteredProductHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={enteredProduct}                    /><TextInput keyboardType = "number-pad"                     placeholder="Ilość"                     style={styles.input}                     onChangeText={ammountHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={ammount}                    /><View style = {styles.buttonContainer}><View style = {styles.button}><Button color = {colors.accent} title = 'Dodaj' onPress = {confirmProduct}/></View><View style = {styles.button}><Button title = 'Wyjdź' color = {colors.accent} onPress={returnToMainScreen}/></View></View></Card> </View></TouchableWithoutFeedback>    );};const styles = StyleSheet.create({    screen:    {        justifyContent:'center',        alignItems:'center',    },    inputContainer:{        flex: 0.5,         justifyContent:'center',        alignItems:'center'      },      input:{        height:30,        borderBottomColor: 'grey',        borderBottomWidth: 1,        marginVertical: 13,      },      buttonContainer:{          flexDirection:'row',          alignItems: 'center',          justifyContent: 'space-between' ,          width: '60%'      },      button:{          width:'40%',      }  });  export default AddingScreen;

The data which i'm sending is in function:

function confirmProduct()   {       props.navigation.navigate('Main',{input:enteredProduct});       setEnteredProduct('');       setAmmount('');   }

And there is second screen:

import { StatusBar } from 'expo-status-bar';import React, {useState} from 'react';import {   StyleSheet,   View,   Button,   VirtualizedList,  Alert,} from 'react-native';import GoalItem from'../components/Goalitem';import Header from '../components/Header';import colors from '../constants/colors';type Props={  navigation:any}const MainScreen = (props:Props) =>{  //var inputFromAdding = JSON.stringify(props.navigation.getParam('input'));  const [products, setProducts]  = useState<any>([]);  const [ammont, setAmmount] = useState<any>([])  function addProduct(goalTitle: any):any  {    //if(goalTitle.length === 0) return;    setProducts([...products,{id: Math.random().toString(), value: goalTitle}]);     return products;  };  function removeGoalHandler(goalId:any):void  {    setProducts((courseGoals: any[]) =>     {      return courseGoals.filter((goal:any) => goal.id !== goalId);    });  };  function deleteListAlert():void  {    if(products.length >0)    {      Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?',        [{text: 'Tak', style: 'destructive', onPress: deleteList},         {text: 'Nie', style: 'cancel'}]);    }    else{      Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.',        [{text: 'Powrót', style: 'cancel'}]);    }  }  function deleteList()  {    setProducts('')  }  //let xx = ;  return (<View style = {styles.screen}><Header title="Lista zakupów"/><VirtualizedList         keyExtractor={(item:any, index) => item.id}        data ={addProduct(JSON.stringify(props.navigation.getParam('input')))}         renderItem ={itemData => (<GoalItem           id = {itemData.item.id}           onDelete = {removeGoalHandler}           title = {itemData.item.value}           />        )}      /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {colors.accent} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {colors.accent} title="+" onPress = {() => {            props.navigation.navigate('Adding')          }}/></View></View></View>  );}const styles = StyleSheet.create({  screen:{   flex:1,   backgroundColor: 'white',  },  button:{    width: 40,  },  button1:{    width: 90,  },  buttonPosition:{    padding:15,    alignItems: 'stretch',    justifyContent: 'space-between',    flexDirection:'row',    backgroundColor: colors.primary,  },});export default MainScreen;

I'm reciving the data in:

data ={addProduct(JSON.stringify(props.navigation.getParam('input')))} 

and adding it in function:

  function addProduct(goalTitle: any):any  {    //if(goalTitle.length === 0) return;    setProducts([...products,{id: Math.random().toString(), value: goalTitle}]);     return products;  };

than returns products, which is my array of values that i'm rendering below.

The error is: Component Excepiton: Too may re-renders. React limits the number of renders to prevent an infinite loop.


ERROR Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'LinkingManager' could not be found

$
0
0

I am facing a flowing issue ERROR Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'LinkingManager' could not be found. Verify that a module by this name is registered in the native binary.

I have removed node_model folder and reinstalled it, but showing the same issue.

Is it already possible to use top-level await in react-native?

$
0
0

Is it already possible to use top-level await in react-native? I saw it's been added to TypeScript 3.8 (I was not using TS, I just tried to see if it would help but no). However in react-native file transform is handled by babel and I don't think the current metro preset handles top-level awaits. Is there any way to make it work?

React native with typescript - how to use the useRoute from @react-navigation/native with typescript

$
0
0

I'm trying to get my incident object from route.params but I don't know how to do it to make typescript recognize this prop.

Here is the function that navigate to my Detail page passing incident to params:

const navigateToDetail = (incident: IncidentProps): void => {    navigation.navigate('Detail', { incident });  };

And Here is part of Detail page code where I try to get this object from route.params:

type IncidentRouteParams = {  incident: IncidentProps;}const Detail: React.FC = () => {  const navigation = useNavigation();  const route = useRoute();  const incident = route.params.incident;

I think I need to pass this IncidentRouteParams type somehow to const route = useRoute()

Thanks in advance.

Here is the image with the error:

EDIT:

I did like this, and it worked, but I don't know if it is the right way:

  const route = useRoute<RouteProp<Record<string, IncidentRouteParams>, string>>();  const incident = route.params.incident;

Cannot re-render flatlist using boolean toggle

$
0
0

I'm struggling to re-render a flatlist. I'm trying to use a boolean refreshToggle, that is fed into extraData, that is changed after the desired information is successfully fetched. The code below successfully fetches the data and changes the boolean (so changing to functional updates for the state, while perhaps better practice, doesn't seem like a solution) (I've checked that this is happening with various logs etc), but the flatlist doesn't re-render.

export default function transactions({ navigation }: { navigation: any }) {    const [paymentsBtnActive, setPaymentsBtnActive] = React.useState<boolean>(navigation.getParam('Pressed') == 'Payments');    const [requestsBtnActive, setRequestsBtnActive] = React.useState<boolean>(navigation.getParam('Pressed') == 'Requests');    const [refreshToggle, setRefreshToggle] = React.useState<boolean>(false);    let data: any[] = [];    async function getRequests() {        const body = { 'phone': GLOBAL.userInfo['phone']        }        const options = {            method: 'POST',            headers: { 'Content-Type': 'application/json'},            body: JSON.stringify(body)        }        let requests =  await fetch('http://3ef68e9c1352.ngrok.io/requests/user', options);        let requestsJSON = await requests.json();        data = requestsJSON['data'];    }        function renderItem(item: any) {        console.log(item)        return (<Text>{item['item']['data']['date']}</Text>)    }    function listEmpty(){        return (<Text>Loading</Text>)    }    useEffect(() => {        (async function () {            console.log('In useEffect (1)')            await getRequests();            setRefreshToggle(!refreshToggle)        })()    }, [])    return (<SafeAreaView style = {styles.container}><View style = {{flexDirection: 'row', justifyContent: 'center'}}><TouchableOpacity style = { paymentsBtnActive ? styles.paymentsBtnActive : styles.paymentsBtnInactive } onPress = { () => { setRequestsBtnActive(paymentsBtnActive)                     setPaymentsBtnActive(!paymentsBtnActive) } } ><Text style = { paymentsBtnActive ? styles.whiteText : styles.redText }>Payments</Text></TouchableOpacity><TouchableOpacity style = { requestsBtnActive ? styles.requestsBtnActive : styles.requestsBtnInactive } onPress = { () => { setPaymentsBtnActive(requestsBtnActive)                    setRequestsBtnActive(!requestsBtnActive) } }  ><Text style = { requestsBtnActive ? styles.whiteText : styles.redText }>Requests</Text></TouchableOpacity></View><View style = {styles.summaryView}><FlatList                     data={data}                     renderItem={renderItem}                     ListEmptyComponent = {listEmpty}                    extraData = {data[0]}                /></View></SafeAreaView>    );

how to solve the onClick problem in typescript Reactjs

$
0
0

my function is like this:

async function handleFavorites(event: MouseEvent) { event.preventDefault();}

on my button, I'm using onclick to call this function but it's not working

<button type="submit" value={favorites} onChange={e => setFavorites(e.currentTarget.value)} onClick={() => {    handleFavorites(); }}>

Error: Expected 1 arguments, but got 0.An argument for 'event' was not provided.

does anyone know how to solve? or have any tips?

Viewing all 6288 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>