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

Problem with passing data between screens

$
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 [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;

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

import { StatusBar } from 'expo-status-bar';import React, {useState, useEffect} from 'react';import {   StyleSheet,   View,   Button,   FlatList,  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) =>{  let inputFromAdding = JSON.stringify(props.navigation.getParam('input'));  const [products, setProducts]  = useState<any>([]);  const [ammont, setAmmount] = useState<any>([])  function addProduct(goalTitle: any):any  {    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('')  }  return (<View style = {styles.screen}><Header title="Lista zakupów"/><FlatList         keyExtractor={(item:any, index) => item.id}        data ={products}         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:

let inputFromAdding = JSON.stringify(props.navigation.getParam('input'));

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 function in FlatList in prop data, that change the state with setProducts and returns products as my uploaded array, but i've got an error "Component Exception: Too many re-renders", also try to use globalState but it doesn't work. Maybe somebody can help me, thanks for help :)


Viewing all articles
Browse latest Browse all 6287

Trending Articles