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

Porblem with passing data between screen (Too many re-renders)

$
0
0

I've got 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 { useGlobal } from 'reactn';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 [amount, setAmount] = useState<any>('');    function enteredProductHandler(enteredText:string):void    {        setEnteredProduct(enteredText);    }    function amountHandler(enteredText:any):void    {        let amountAndProduct;        const amm = parseInt(enteredText);        if(isNaN(enteredText) || enteredText > 1)        {            setAmount(enteredText);            amountAndProduct = enteredText +''+ enteredProduct;            annmountAndProductToSend = amountAndProduct;        }        else setAmount('')    }    function confirmProduct()    {        props.navigation.navigate('Main',{input:enteredProduct});        setEnteredProduct('');        setAmount('');    }    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={amountHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={amount}                    /><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;

And here is the screen, where i'm passing this data (input) to add it to VirtualizedList:

import { StatusBar } from 'expo-status-bar';import React, {useState, useContext} 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}//setProducts([...products,{id: Math.random().toString(), value: props.navigation.getParam('input')}]); const MainScreen = (props:Props) =>{  const [products, setProducts]  = useState<any>([]);  const [didAddInput, setDidAddInput] = useState<boolean>(false);  const [amont, setAmount] = useState<any>([]);  function addProduct(input:string,oneadd:boolean){   setDidAddInput(oneadd);  if(didAddInput === true)  {    setProducts([...products,{id: Math.random().toString(), value: input}]);     return products;  }  setDidAddInput(false)  };  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('')  }  function count():number  {    return 50;  }  return (<View style = {styles.screen}><Header title="Lista zakupów"/><VirtualizedList         keyExtractor={(item:any, index) => item.id}        //data ={addProduct(value)}         getItem = {addProduct(JSON.stringify(props.navigation.getParam('input')),true)}        getItemCount = {count}        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;

So my data is here:

getItem = {addProduct(JSON.stringify(props.navigation.getParam('input')),true)}

I put it in console.log and it's sent right, but i've got a problem with adding it to

const [products, setProducts]  = useState<any>([]);

(products is my array of values)

I try to put a second useState to avoid multiple adding by changing state to false after adding but it changes nothing, i've got an error "Component Exception: Too many re-renders", also try to use globalState but it doesn't work. Maybe there is another and better way to change the state with input data, thanks for help :)


Viewing all articles
Browse latest Browse all 6287

Trending Articles



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